編輯:進階開發
DDMS 中最能體現 NIO 框架的,莫過於 MonitorThread.java。它是整個 PC 端同步架構的心臟,值得逐段拆解。
final class MonitorThread extends Thread {
private static final int CLIENT_READY = 2;
private static final int CLIENT_DISCONNECTED = 3;
private volatile boolean mQuit = false;
private ArrayList<Client> mClientList; // 客戶端清單
private Selector mSelector;
private HashMap<Integer, ChunkHandler> mHandlerMap; // 訊息處理器表
private ServerSocketChannel mDebugSelectedChan; // 調試用通道
private int mNewDebugSelectedPort;
private int mDebugSelectedPort = -1;
private Client mSelectedClient = null;
private static MonitorThread mInstance;
static MonitorThread createInstance() { return mInstance = new MonitorThread(); }
static MonitorThread getInstance() { return mInstance; }
}
單例 + 執行緒的組合,讓整個應用共用一條事件迴圈。mQuit 宣告為 volatile 是必要的——它會被其他執行緒寫入,若沒有 volatile,JIT 可能把讀取最佳化為暫存器值,導致迴圈永遠不會結束。
實務建議:mHandlerMap 在多執行緒環境下被讀寫,用 ConcurrentHashMap 會比 HashMap 加外部 synchronized 更清晰、也更高效。
@Override
public void run() {
Log.d("ddms", "Monitor is up");
try {
mSelector = Selector.open();
} catch (IOException ioe) {
Log.logAndDisplay(LogLevel.ERROR, "ddms",
"Failed to initialize Monitor Thread: " + ioe.getMessage());
return;
}
while (!mQuit) {
try {
// 必要時重開 debug-selected 埠
if (androidDebugBridge.getClientSupport()
&& (mDebugSelectedChan == null
|| mNewDebugSelectedPort != mDebugSelectedPort)
&& mNewDebugSelectedPort != -1) {
if (reopenDebugSelectedPort()) {
mDebugSelectedPort = mNewDebugSelectedPort;
}
}
int count = mSelector.select();
if (count == 0) continue;
Set<SelectionKey> keys = mSelector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove(); // 關鍵:一定要移除
try {
if (key.attachment() instanceof Client) {
processClientActivity(key);
} else if (key.attachment() instanceof Debugger) {
processDebuggerActivity(key);
} else if (key.attachment() instanceof MonitorThread) {
processDebugSelectedActivity(key);
}
} catch (Exception e) {
Log.e("ddms", "Exception during activity from Selector.");
Log.e("ddms", e);
}
}
} catch (CancelledKeyException cke) {
continue;
} catch (Exception e) {
Log.e("ddms", "Exception MonitorThread.run()");
Log.e("ddms", e);
}
}
}
這裡有兩個值得學的設計:
用 attachment 做事件分派。 註冊時把 Client、Debugger 或 MonitorThread 自身當作附件掛在 key 上,處理時用 instanceof 判斷即可分流,不必維護額外的對應表。
例外隔離在每個 key 的層級。 單一連線出問題不該讓整條迴圈中斷,因此 try/catch 放在 per-key 而非 per-loop。相對地,CancelledKeyException 在外層攔下直接 continue,這是 Selector 編程的必要防護。
原始碼在 count == 0 時直接 continue 這段,註解裡也坦承寫得不算好——這種忙等在 PC 端影響不明顯,但若放到高負載伺服器上,CPU 佔用會相當可觀。
private void processClientActivity(SelectionKey key) {
Client client = (Client) key.attachment();
try {
if (key.isReadable() == false || key.isValid() == false) {
dropClient(client, true);
return;
}
client.read();
JdwpPacket packet = client.getJdwpPacket();
while (packet != null) {
if (packet.isDdmPacket()) {
callHandler(client, packet, null);
packet.consume();
} else if (packet.isReply()
&& client.isResponseToUs(packet.getId()) != null) {
ChunkHandler handler = client.isResponseToUs(packet.getId());
if (packet.isError()) client.packetFailed(packet);
else if (packet.isEmpty()) Log.d("ddms", "Got empty reply");
else callHandler(client, packet, handler);
packet.consume();
client.removeRequestId(packet.getId());
} else {
client.forwardPacketToDebugger(packet);
}
packet = client.getJdwpPacket();
}
} catch (CancelledKeyException e) {
dropClient(client, true);
} catch (IOException ex) {
dropClient(client, true);
} catch (Exception ex) {
if (ex instanceof BufferOverflowException) {
Log.w("ddms", "Client data packet exceeded maximum buffer size");
}
dropClient(client, true);
}
}
三個細節:isReadable() && isValid() 的雙重檢查、封包用迴圈逐個取出(一次 read 可能含多個封包)、以及 BufferOverflowException 的專門處理。
private void callHandler(Client client, JdwpPacket packet, ChunkHandler handler) {
if (!client.ddmSeen()) broadcast(CLIENT_READY, client);
ByteBuffer buf = packet.getPayload();
int type = buf.getInt();
int length = buf.getInt();
if (handler == null) {
synchronized (mHandlerMap) {
handler = mHandlerMap.get(type);
}
}
if (handler == null) {
Log.w("ddms", "Received unsupported chunk type " + ChunkHandler.name(type));
} else {
ByteBuffer ibuf = buf.slice();
ByteBuffer roBuf = ibuf.asReadOnlyBuffer(); // 強制唯讀
roBuf.order(ChunkHandler.CHUNK_ORDER);
synchronized (mClientList) {
handler.handleChunk(client, type, roBuf, true, packet.getId());
}
}
}
asReadOnlyBuffer() 這招很值得學:把資料交給外部 handler 之前先轉為唯讀視圖,從源頭杜絕 handler 誤改原始緩衝區。 buf.slice() 則建立一個共用底層記憶體但獨立 position/limit 的視圖,讓每個封包各自游標,互不干擾。
private boolean reopenDebugSelectedPort() throws IOException {
if (mDebugSelectedChan != null) mDebugSelectedChan.close();
mDebugSelectedChan = ServerSocketChannel.open();
mDebugSelectedChan.configureBlocking(false); // Selector 要求非阻塞
InetSocketAddress addr = new InetSocketAddress(
InetAddress.getByName("localhost"), mNewDebugSelectedPort);
mDebugSelectedChan.socket().setReuseAddress(true); // SO_REUSEADDR
try {
mDebugSelectedChan.socket().bind(addr);
if (mSelectedClient != null) {
mSelectedClient.update(Client.CHANGE_PORT);
}
mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this);
return true;
} catch (java.net.BindException e) {
displayDebugSelectedBindError(mNewDebugSelectedPort);
mDebugSelectedChan = null;
mNewDebugSelectedPort = -1;
return false;
}
}
setReuseAddress(true) 對應 SO_REUSEADDR,讓程式重啟後能立刻綁回同一個埠,避開 TIME_WAIT 期的 BindException。這在需要頻繁重啟的開發工具上很重要。
synchronized void quit() {
mQuit = true;
wakeup(); // 喚醒阻塞中的 select()
try {
this.join();
synchronized (mClientList) {
for (Client c : mClientList) c.close(false);
mClientList.clear();
}
if (mDebugSelectedChan != null) {
mDebugSelectedChan.close();
mDebugSelectedChan.socket().close();
mDebugSelectedChan = null;
}
mSelector.close();
} catch (InterruptedException IE) {
IE.printStackTrace();
} catch (IOException e) { }
mInstance = null;
}
private void wakeup() {
mSelector.wakeup(); // 讓阻塞在 select() 的執行緒立刻返回
}
quit() 一定要先呼叫 wakeup(),否則主執行緒可能永遠卡在 select() 上,join() 也就永遠等不到。這是 Selector 生命週期管理最經典的一課。
DDMS 的 PC 端程式碼,老實說品質參差不齊:不少地方靠縫補解決問題,習慣也談不上到位。但它仍是少見的、可讀的真實 NIO 框架範例。由於牽涉的物件眾多(Client、Debugger、JdwpPacket、ChunkHandler、DeviceMonitor 彼此交錯),建議先畫出 UML 類別圖理清關係,再回頭讀程式碼,會順暢得多。
若要用這份架構做為自己專案的參考,記得補上 DDMS 沒做好的部分:每連線獨立的讀寫緩衝區、interestOps 取代重複 register、以及避免 select() 忙等。把這些補齊,你就有了一個真正能上場的骨架。
Android Widget 設計指南:尺寸、框架與陰影規範
Widget 是 Android 1.5 版引入的特性之一,讓使用者不必打開應用,就能在主螢幕上直接看到程式的重要資訊。標準 Android 系統已內建幾個範例,例如模擬
Android UI 設計入門:View、ViewGroup 與 Layout 的關係
Android 由作業系統、中間件、使用者介面與應用軟體組成,而一個應用能否受使用者青睞,UI 往往是最後的決勝點。本文梳理 Android UI 體系的三個核心概念,並
Android 原始碼結構(4):external 與 Java 套件該去哪找
Android 的擴充專案收在 external 資料夾中,是一些改寫過、適應 Android 系統的開源專案。有些在主機上執行,有些在目標裝置上執行。因為數量太多就不逐
Android 建立 sdcard 模擬記憶卡完整圖解
Android 的應用方式相當靈活,在模擬器中做適當設定就能滿足許多特定的功能需求,例如需要外部儲存空間的相機、錄音或檔案讀寫測試。本文說明如何建立並啟用 sdcard