等待 Zookeeper 客户端线程停止

Wait for Zookeeper client threads to stop

Zookeeper 客户端启动时,它会创建 2 个线程:SendThreadEventThread

在应用程序关闭时,我希望工作线程等待 Zookeeper 线程完成,但在 API.

中看不到任何合适的内容

然而我只能调用 ZooKeeper.close() 将连接状态设置为 CLOSED 并为 EventThread 排队“死亡事件”。

来自 ClientCnxn:

public void disconnect() {    
    this.sendThread.close();
    this.eventThread.queueEventOfDeath();
}
 

我错过了什么吗? 有没有办法在不修改 ZK 客户端代码的情况下加入 Zookeeper 线程?

没有合适的 API 存在,所以最后不得不通过反思来做到这一点:

        Field cnField = ZooKeeper.class.getDeclaredField("cnxn");
        cnField.setAccessible(true);
        ClientCnxn cnxn = (ClientCnxn) cnField.get(zoo);
        Field sendField = ClientCnxn.class.getDeclaredField("sendThread");
        sendField.setAccessible(true);
        Field eventField = ClientCnxn.class.getDeclaredField("eventThread");
        eventField.setAccessible(true);
        Thread sendThread = (Thread) sendField.get(cnxn);
        Thread eventThread = (Thread) eventField.get(cnxn);
        sendThread.join();
        eventThread.join();