Originally posted by Pradeep Bhat: Hello Scott/Henry,
Could you please explain what Condition Variables are all about?
I am assuming you are asking about the condition variables that were added to JDK 1.5... Anyway, there is a short and long answer here.
The short answer: Condition variables are simply classes that implemented the wait() and notify() functionality.
The long answer: JDK 1.5 added a locking class (that implements the Lock interface). Basically this class provides explicit locking. There were multiple reason why it was added -- instead of just using the synchronized keyword.
First, is scope. With synchronized, the only scope available were at a block or method level. With an explicit locks, the scope can be multiple methods, it can be based on a user session, or data model, or any scope you want.
Second, is usage. You can have many locks in an object. You can share a lock among many objects, or any combinations you like.
Condition variables are the wait-and-notify counterpart to the lock class. If you use this new lock class, you need to use the new condition class.
Also, the condition variable is an independent object. A lock can have mulitple condition variables. A classic case is of a buffer. You need one lock to protect the buffer, but many need multiple condition variables; one when the buffer is empty waiting for data, one when the buffer is full waiting for space. Without separate condition variables, you typically have to use a notify all instead of just a notify on the specific condition variable.