zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    struct&Method
    SetFinalizer、runtime.GC
    Map(没有写底层)
    数组和切片
    函数
    指针、Time
    字符串、strings、strconv
    基本类型和运算符
    第二阶段的事后诸葛亮
    第二个冲刺阶段第10天
  • 原文地址:https://www.cnblogs.com/devos/p/3734964.html
Copyright © 2011-2022 走看看