Click here to Skip to main content
15,881,027 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
we have the following pattern
Java
lock = new reentrantlock(true);

...

if(x = 1)
{
do{
cond.lock()}while(x = 1);
}

assume there are multiple threads.

is a starvation scenario possible?

we're calling cond.lock as long as condition is true, if condition is always true, it will lead to a starvation, if condition is true whenever the signal() method is called, it will also lead to a starvation. am i right? any solution to this?
Posted
Updated 16-Nov-13 8:12am
v2

1 solution

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
 
Share this answer
 
v2
Comments
pasztorpisti 17-Nov-13 8:43am    
5.
Sergey Alexandrovich Kryukov 17-Nov-13 13:33pm    
Thank you.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900