這算是CountDownLatch的一個典型使用場景。
kafka.Kafka對象的main方法中與此有關的代碼為
// attach shutdown handler to catch control-c Runtime.getRuntime().addShutdownHook(new Thread() { override def run() = { kafkaServerStartble.shutdown } }) kafkaServerStartble.startup kafkaServerStartble.awaitShutdown System.exit(0)
首先,注冊一個shutdownHook,在control-c等令虛擬機停止命令后,虛擬機會啟動被注冊的hook對應的線程,在這里,server的shutdown方法將被調用。
然后,啟動server。在server的startup方法中,會初始化一個CountDownLatch為1。這時,server的各個子服務開始運行。
然后,調用server的awaitShutdown方法,使得main線程阻塞。
def awaitShutdown(): Unit = shutdownLatch.await()
這個方法就是簡單地調用CountDownLatch的await方法。而之前提到的,server的shutdown方法就是在停止server的各個服務后,調用CountDownLatch的countDown方法,這時,阻塞在await的main線程就會醒來,從而調用System.exit。
綜上,control-c 使shutDown在shutDownHook的線程中被調用,從而使CountDownLatch減1,使得之前阻塞在同一個CountDownLatch的main線程繼續,從而調用 System.exit推出JVM。