Very bad, wrong pattern which does not cause deadlock but is the total waste of CPU time. Besides,
x
is supposed to be used as a shared variable (otherwise it the loop will never break), and the access to it is not interlocked, while
cond.lock
is simply irrelevant. Wasting of CPU time may or may not lead to "starvation", but it is obvious that the more you use wrong threading patterns related to the waste of CPU time, the more likely the starvation can be. :-)
No need to fix this code; the whole idea is wrong. Probably, you simply want to keep one thread waiting until some other thread let it go. This is basically done by using Java wait/notify mechanism. See for example:
http://www.javamex.com/tutorials/synchronization_wait_notify.shtml[
^].
See also this article:
http://tutorials.jenkov.com/java-concurrency/thread-signaling.html[
^].
The mechanism you should chose in a certain situation really depends on the purpose of making thread waiting. If you want to keep some thread waiting until some set of operation is complete by another thread, this can be achieved through using the class
CountDownLatch
:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html[
^].
This is a similar synchronization class with resettable count operating on a set of threads:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html[
^].
Note that the waiting thread does not waste any CPU time. The approach is actually based on the mechanism of preemption (through hardware interrupts triggering events when a thread could be preempted) and thread scheduling in the OS which is mapped on the properly implemented Java machine operation. A thread is put in the wait state and is not scheduled back to execution until it is waken up by setting certain condition.
—SA