Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is better for performance to check another threads boolean in java

while(!anotherThread.isDone());

or

while(!anotherThread.isDone())
    Thread.sleep(5);
like image 332
Vig Avatar asked Dec 02 '22 23:12

Vig


2 Answers

If you really need to wait for a thread to complete, use

anotherThread.join()

(You may want to consider specifying a timeout in the join call.)

You definitely shouldn't tight-loop like your first snippet does... and sleeping for 5ms is barely better.

If you can't use join (e.g. you're waiting for a task to complete rather than a whole thread) you should look at the java.util.concurrent package - chances are there's something which will meet your needs.

like image 172
Jon Skeet Avatar answered Dec 17 '22 00:12

Jon Skeet


IMHO, avoid using such logic altogether. Instead, perhaps implement some sort of notification system using property change listeners.

like image 23
mre Avatar answered Dec 16 '22 23:12

mre