Kafka server的的停止

这算是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。

posted @ 2014-05-18 11:05  devos  阅读(7342)  评论(1编辑  收藏  举报