Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

NIO 非阻塞入門(八):以 MonitorThread 剖析 Selector 框架

編輯:進階開發

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 的專門處理。

分派訊息給 handler

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() 忙等。把這些補齊,你就有了一個真正能上場的骨架。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved