Why must KafkaServer be thread-safe

Viewed 83

I've been Kafka user for a while and today I have to read its core source code.

Well, I've found that the code about starting a Kafka broker was here: https://github.com/apache/kafka/blob/trunk/core/src/main/scala/kafka/server/KafkaServer.scala

In this scala file, there is a function startup(), which is invoked when we start a Kafka broker.

What makes me confused is that it seems that some atomic variables are used to keep this function thread-safe. As you can see there are some atomic boolean variables, such as isShuttingDown, startupComplete, isStartingUp.

def startup(): Unit = {
    try {
      info("starting")

      if (isShuttingDown.get)
        throw new IllegalStateException("Kafka server is still shutting down, cannot re-start!")

      if (startupComplete.get)
        return

      val canStartup = isStartingUp.compareAndSet(false, true)
      if (canStartup) {
        brokerState.newState(Starting)

        /* setup zookeeper */
        initZkClient(time)
        ...
        ...

But I kind of don't know why we need such a thread-safe mechanism. As my understanding, one process of Kafka broker has only one KafkaServer, which means that the function startup has only one chance to be executed. If we try to start more than one process of Kafka broker in a short period on the same machine, it's just a inter-process issue, instead of multi-threading issue. Thread-safe doesn't seem to be necessary.

Can someone tell me why some atomic variables are used here? Why is thread-safe necessary here?

0 Answers
Related