Java: Is `while (true) { ... }` loop in a thread bad? What's the alternative?

52,786

Solution 1

Instead of looping forever and breaking or returning, you might choose to check the interrupted status.

while (!Thread.currentThread().isInterrupted()) {
    try {
        doWork();
        wait(1000);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}

If your threads are tasks managed by an ExecutorService, you can have them all end gracefully simply by calling shutdownNow().

Solution 2

while (!stop_running) { ... }

...perhaps? A some sort of exit flag is often used to control thread running.

Solution 3

Not inherently, no. You can always bail using break or return. Just make sure you actually do (at some point)

The problem is what happens when your thread has nothing to do? If you just loop around and around checking a condition, your thread will eat up the whole CPU doing nothing. So make sure to use wait to cause your thread to block, or sleep if you don't have anything to wait on.

Solution 4

Depends on the definition of "bad". It means that the person trying to read the code has to look elsewhere for the reason that the loop is terminated. That may make it less readable.

This mentality taken to the extreme results in the COMEFROM keyword. http://en.wikipedia.org/wiki/COMEFROM

10 COMEFROM 40
20 INPUT "WHAT IS YOUR NAME? "; A$
30 PRINT "HELLO, "; A$
40 REM

Solution 5

Although all the above answers are correct, I want to suggest this one as I came across this situation myself: You can use a flag say:

isRunning=true;
while(isRunning){
   //do Something
}

Later, make sure that isRunning is set to false after you are done reading from the buffer or data file.

Share:
52,786
Mr. Burgundy
Author by

Mr. Burgundy

Updated on September 25, 2021

Comments

  • Mr. Burgundy
    Mr. Burgundy over 2 years

    Is while (true) { ... } loop in threads bad? What's the alternative?

    Update; what I'm trying to to...

    I have ~10,000 threads, each consuming messages from their private queues. I have one thread that's producing messages one by one and putting them in the correct consumer's queue. Each consumer thread loops indefinitely, checking for a message to appear in their queue and process it.

    Inside Consumer.java:

    @Override
    public void run() {
        while (true) {
            Message msg = messageQueue.poll();
            if (msg != null) {
                ... // do something with the message
            }
        }
    }
    

    The Producer is putting messages inside Consumer message queues at a rapid pace (several million messages per second). Consumers should process these messages as fast as possible!

    Note: the while (true) { ... } is terminated by a KILL message sent by the Producer as its last message. However, my question is about the proper way to do this message-passing...

    Please see the new question, regarding this design.