Thread.yield() considered harmful?
The main problem with calling Thread.yield()
in a while loop without any wait mechanics is that it easily becomes a busy-wait loop using 100% of one of your cores.
If there are no other threads to schedule when you yield, the yielded thread will probably be re-scheduled very quickly and hence resulting in high CPU utilization.
Other than that, in this case, I can't see it would be more harmful than that. However, it is pretty pointless - if you are going to write a busy-wait loop you could just do while (!foo.isInitialized());
and avoid stressing the scheduler.
What you should do, if you cannot have a notify mechanism, is to at least sleep in the loop. This will allow your CPUs to rest a bit.
Typical implementation of such a loop:
while(!foo.isInitialized()) { try { Thread.sleep(20); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; // or handle some other way }}