In Java, a condition variable is a synchronization primitive that can be used to manage threads that are waiting for a certain condition to be met before proceeding. It is typically used in conjunction with a Lock object (e.g. ReentrantLock) to provide finer-grained control over thread synchronization.
The Condition interface in Java provides methods for waiting on a condition and signaling when the condition has been met. Here’s an example of how a Condition object can be used to manage a thread that is waiting for a shared resource:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MyResource {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean resourceAvailable = false;
public void getResource() throws InterruptedException {
lock.lock();
try {
while (!resourceAvailable) {
condition.await();
}
// Access shared resource here
resourceAvailable = false;
condition.signal();
} finally {
lock.unlock();
}
}
public void setResource() throws InterruptedException {
lock.lock();
try {
while (resourceAvailable) {
condition.await();
}
// Set shared resource here
resourceAvailable = true;
condition.signal();
} finally {
lock.unlock();
}
}
}
In this example, a ReentrantLock object is used to protect a shared resource that can be accessed by multiple threads. The getResource() method is called by a thread that needs to access the resource, and the setResource() method is called by a thread that needs to update the resource.
The Condition object is used to manage the waiting and signaling of threads that are blocked on the shared resource. In the getResource() method, the thread enters a loop and calls the await() method on the Condition object while the resource is not available. When the resource becomes available, the thread exits the loop and accesses the shared resource.
Similarly, in the setResource() method, the thread enters a loop and calls the await() method while the resource is available. When the resource is no longer being used, the thread updates the shared resource and signals any waiting threads by calling the signal() method on the Condition object.
Overall, condition variables provide a powerful way to manage thread synchronization in Java by allowing threads to wait on a specific condition before proceeding. By using a Condition object in conjunction with a Lock object, you can achieve finer-grained control over thread synchronization and avoid common synchronization problems like deadlock and livelock.