While working on my Java application, I've a simple multithreading case (one asynchronous resource loader thread and one main thread waiting for the loader to finish, updating the UI with the progress), which I figured to solve by calling
while( !foo.isInitialized() ) {
Thread.yield();
}
in the main thread. I'm aware that there are more robust solutions; still, the loader is not designed by me and it's a basically read-only library (I can't simply wait()
, because I can't make it send me a notify()
; also, it doesn't die after finishing), and I just need to wait until the loading is done.
Java doc says that (note this was not present in 1.6 docs and was added by 1.7 docs)
It is rarely appropriate to use this method.
NetBeans warns me that
Invocation of method
yield()
onjava.lang.Thread
is usually used to masquerade synchronization problems and should be avoided.
Google Codepro AnalytiX, OTOH, says
The method
Thread.yield()
should not be used because its behavior is not consistent across all platforms.
Should I be concerned with those warnings and try to find a better solution (all suggestions are welcome), or should I consider those as "warning noise" and suppress/ignore them?
Note: I thought about the obvious possibility of using sleep()
(Are Thread.sleep(0) and Thread.yield() statements equivalent? is worth mentioning here); still, if yield
ing has no "bonus" over constantly sleeping, why does Java provide it at all - and what are the actual valid use cases for it then?
Slightly related: Is there a better solution to Thread.yield()? & Thread.Sleep or Thread.Yield
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: