在阅读ZooKeeper的源码时,看到这么一个片段,在单机模式启动的时候,会调用下面的方法,根据zoo.cfg的配置启动单机版本的服务器:

public void runFromConfig(ServerConfig config) throws IOException {
//1 创建ZooKeeper服务器
final ZooKeeperServer zkServer = new ZooKeeperServer();
final CountDownLatch shutdownLatch = new CountDownLatch(1);
zkServer.registerServerShutdownHandler(
new ZooKeeperServerShutdownHandler(shutdownLatch));
...
//2 创建ZooKeeper的NIO线程
cnxnFactory = ServerCnxnFactory.createFactory();
cnxnFactory.configure(config.getClientPortAddress(),
config.getMaxClientCnxns());
cnxnFactory.startup(zkServer);

// 3 调用shutdownLatch阻塞,服务器在新线程正常处理请求
shutdownLatch.await();
// 4 如果有错误,直接调用shutdown
shutdown();
// 5 执行cnx.join()等待NIO线程关闭
cnxnFactory.join();
if (zkServer.canShutdown()) {
zkServer.shutdown(true);
}
}
...
protected void shutdown() {
if (cnxnFactory != null) {
cnxnFactory.shutdown();
}
}


其中比较有意思的两个地方:

1 CountDownLatch的使用

开启NIO新线程接收客户端的请求,服务端的主线程直接利用countdownlatch挂起。这个CountDownLatch之前有说过,就是个多线程的计数器。

2 join的作用

join的作用就是主线程遇到A.join()之后,就会挂起;登到A结束后,才会继续执行。可以理解为主线程调用了A的wait方法...

下面有个Join的小例子:

public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread A = new Thread(()->{
System.out.println("进入线程A");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A:线程A结束");
});
A.start();

System.out.println("Main:等待线程A结束");
A.join();
System.out.println("Main:线程A已经结束,退出");
}
}


输出内容为:

Main:等待线程A结束
进入线程A
A:线程A结束
Main:线程A已经结束,退出


可以看到,Main线程在A.join()的地方挂起了。等A结束后,才继续执行。

ZooKeeper这样的设计,使服务器在关闭前,确保NIO线程正确关闭,避免NIO资源的未释放。