1: The Condition object is linked (and retrieved from) by the Lock object (aka mutext). The javadoc for the class is clear enough about its use and application. To wait on the condition that you need to get a lock, and it is good coding practice to do this in a try / finally block (like yours). As soon as a thread that has acquired a lock waits for a condition for this lock, the lock will be rejected (atomically).
2: The use of latency is necessary to ensure the viability of your program when the condition that you expect never occurs. Its definitely a more complex form, and it is completely useless if you do not check the fact that you have run out of time and take steps to handle the timeout condition.
Using sleep is an acceptable form of waiting for something, but if you are already using a lock ("mutex") and have a condition variable for this lock, it does not make sense to not use the method to wait for a condition to time :
For example, in your code you simply wait for a given period, but DO NOT check if a condition has occurred or if you have run out of time. (This is a mistake.) What you should do is check if your timed call returned true or false. (If it returns false, then it expires, and the condition has NOT occurred (yet)).
public void myThreadA(){ mutexA.acquire(); try{ while(runningA){ //runningA is a boolean variable if(conditionA.await (sleepATimeoutNanos)) commonActivity(); else { // timeout! anything sensible to do in that case? Put it here ... } } } finally{ mutexA.release(); } }
Q3: [edited] For snippets of code, a more detailed context is required to be clear. For example, it is not entirely clear if the conditions in the threads are all the same (but I assume that they are).
If all you are trying to do is ensure that commonActivity () only runs one thread at a time, and some sections of commonActivity () DO NOT require conflict management, and you require a timeout tool on your expectations, you you can just use semaphore . Note that sempahore has its own set of methods for timed waiting .
If ALL of commonActivity () is critical, and you really don't mind waiting (no timeouts), just make commonActivity () a synchronized method.
[final edit :)] To be more formal about this, conditions are commonly used in scenarios where you have two or more threads interacting with a task and you need manual shutdowns between threads.
For example, you have a server that processes asynchronous responses to user requests, and the user waits for the Future object to complete. In this case, the condition is perfect. A future implementation expects a condition, and the server signals its completion.
In the old days, we will use wait () and notify (), but this was not a very reliable (or trivially safe) mechanism. Lock and Condition objects were designed specifically to address these shortcomings.
(A good online resource as a starting point )
Buy and read this book .