Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who killed My Java Infinite loop thread?

As the title suggested, I have some code wrapped in a while(true) infinite loop, and all of them are fully caught by try and catch block. This thread is started in the main method, however, after long run, this worker thread is vanished mysteriously when I check using the jstack and causing work accumulated.

Below is my code:

public void run() {
    while (true) {
        try {
            // Consumer consumes from Kafka server
            Global.KAFKA_METRIC_DATA_CONSUMER.consume(topic, handler);
        } catch (Exception e) {
            logger.error("Kafka consumer process was interrupted by exception!");
        } finally {
            try {
                // Prevent restart too often
                Thread.sleep(30 * BaseConst.SECOND);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

For my understanding, this structure will keep the thread running so is the consumer. Even if the consume() methods failed, it will restart infinitely. However, as I mentioned above, the whole thread disappear silently without any error log. Could anyone provide some clue please?

Some more information that might be helpful:

  1. I have checked the consume method will never shutdown the consumer nor close the socket to the server. It will continuously try to connect server after fail.
  2. I analysed the java heap dump, and I found there is a memory leak somewhere else in the project, causing memory occupation extremely high and the gc very often. However, the main method is still running.
like image 847
Chen Avatar asked Nov 26 '15 10:11

Chen


1 Answers

OutOfMemoryError is not an Exception. It's an Error derived from Throwable.

If that was thrown somewhere in your consume(topic, handler), finally would still be called, delaying the inevitable some 30s... but after that the error would be passed upward and your loop would be terminated.

like image 124
Jan Avatar answered Sep 25 '22 05:09

Jan