In the previous article, we have Lock and ReentrantLock The core idea was dismantled.
You already know:
synchronizedIt is a built-in lock, simple and directReentrantLockIt is an explicit lock, more flexible and controllablelock()/unlock()To appear in pairs, it is best to always write intry/finallyIntryLock()、lockInterruptibly(), these abilities of fair lock are allsynchronizedhard to express directly
But at this point, many people will immediately ask the next question:
Now that you have learned wait() / notify(), and now Lock, then why does Java have to provide another Condition?
And the first time you see it, it's usually more confusing:
ConditionIsn't it just another wait/wake mechanism?- it and
Object.wait()/notify()What is the essential difference? - Why do documents always say
ConditionCan you provide "multiple waiting queues"? - What practical problems do multiple waiting queues solve?
- when to continue using
wait()/notify(), when is it better to useCondition?
Behind these questions, they are essentially asking:
If the thread communication is upgraded from the "built-in monitor model" to the "explicit lock model", what engineering capabilities are there?
I want to make this article thoroughly.
I will focus on 6 questions:
Conditionwhat is it andwait()/notify()what is the relationship- Why
Conditionmust andLockUse together await()、signal()、signalAll()what are you doing- "Multiple waiting queues" to the end ratio
notifyAll()Where is the strong - Producer-consumer model for
ConditionAfter rewriting, why is it clearer - Which pitfalls should beginners watch for?
You can read this article thoroughly, and then learn it later:
- blocking queue
- Task Coordination in Thread Pool
ReadWriteLock- More complex concurrent containers and synchronizers
will be much smoother.
First, the conclusion: Condition It is not to repeat the wheels, but to dismantle the "conditional waiting" from the built-in lock into a more controllable explicit mechanism
Many people see it for the first time Condition, it will feel that Java seems to have repeated it again wait()/notify().
But what it really solves is not the question of "can wait", but:
When concurrent collaboration becomes complicated, wait()/notify() This model is based on a single monitor waiting queue, and the expression ability is not enough.
You can first understand the relationship between the two:
wait()/notify()/notifyAll(): yessynchronizedConditions in the systemawait()/signal()/signalAll(): yesLockConditions in the system
They are very similar to the goal:
- Wait first when the conditions are not met
- Wake up when the conditions are met
But Condition Two things are emphasized more:
- Wait for the logic to explicitly
- Waiting for the queue to be split
As soon as these two points come out, the readability and controllability of the code will be significantly improved.
Second, why wait()/notify() Not enough? The real problem is "only one waiting queue"
This point is understanding Condition the key to value.
frontal wait()/notify() When we already know:
- Each object can be used as a lock object
- Transfer
wait()The thread will enter the waiting queue associated with this object notify()will wake up one thread at randomnotifyAll()will wake up all threads
It looks fine on the surface.
But once the scene is a little more complicated, the problem comes out.
1) Under a single monitor model, different types of waiting are usually mixed in the same queue
The most classic example is the producer-consumer.
Assuming that the buffer is bounded:
- The buffer is full, the producers have to wait
- The buffer is empty, consumers have to wait
At this point you will find:
"Equal non-fullness" and "waiting non-empty" are actually two completely different conditions.
But if you only use synchronized + wait()/notifyAll(), these two types of threads are often hung in the waiting queue of the same lock object.
So these problems arise:
- The particle size is too thick when awakening
- Obviously it is only time to wake up consumers, but the producers are also woken up
- After many threads are awakened, they find that the conditions are still not satisfied, so they have to continue to sleep and go back.
- The code logic is becoming more and more convoluted
2)notify() I often don't dare to use it indiscriminately, and I can only return it in the end notifyAll()
Because threads of different roles are mixed in the same waiting queue, it is difficult to guarantee:
- Wake up at random this time, it must be the right one
So many codes can only be conservatively written in the end notifyAll().
This is of course safe, but the price is:
- Wake up too many threads
- increase void competition
- Reduce concurrency efficiency
Condition value, it is here that it begins to show.
It allows you to split different conditions into different waiting queues.
That is:
Not all "waiting people" have to be crowded in a room.
Three Condition What is it? It can be understood as "the conditional queue bound to the Lock"
Look at a minimum structure first.
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Demo {
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
}
The most critical sentence here is:
Condition condition = lock.newCondition();
It states:
Condition It does not exist independently, it must be Lock Created on.
Why?
Because the conditional wait is essentially still being coordinated around the same shared data.
Just now:
- mutually exclusive access by
LockTube - Conditions await by
ConditionTube
You can roughly understand it as:
LockResponsible for "Who can enter the door"ConditionResponsible for "After entering, if the conditions are not met, which waiting area to line up"
This is much clearer than a single monitor model.
Four, await()、signal()、signalAll() What are they doing?
These three methods and wait()/notify()/notifyAll() Basically corresponds to the role, but the semantics are closer to the explicit lock system.
1)await(): wait for the condition and release the current lock
the core point and wait() Same:
When threads wait, they will not always occupy the lock.
That is, the thread call await() After that:
- enter the
Conditionwaiting queue - Release the currently held lock
- suspend execution
- wait for others
signal()orsignalAll() - Re-compete lock after being awakened
- After getting the lock again,
await()continue to execute
This process is very important, because many people will mistakenly think that "continue to run immediately after being awakened".
Actually not.
Wake-up only goes back to the lock competition phase from the conditional queue.
It also has to get the lock again before it can really continue.
2)signal(): wake up the Condition Waiting for a thread in the queue
Note a few key words:
- It is this
Conditionwaiting thread - not all threads
- Nothing else
Conditionthread on
This means that you can precisely wake up a certain type of waiter.
3)signalAll(): wake up the Condition Waiting for all threads in the queue
This and notifyAll() Similar, but the scope is more clear:
Only wake up all threads in this conditional queue, not all the people who may be waiting for the same lock.
This is where it is more refined than the traditional monitor model.
5. Why Condition must and Lock Use together?
This is a point that is easy to memorize but not really understand.
The essence is simple:
A thread always waits for a condition on shared state. Access to that state must follow the same mutual exclusion rules throughout.
For example:
- Is the buffer empty
- Is the current inventory is 0
- Whether a task is completed
- Whether a flag has been updated
These conditions are not concepts floating in the air, but part of the shared data.
Therefore, if the waiting condition and the access shared state are not under the same lock protection, the observation between the threads will be inconsistent, and the program will become unreliable.
Therefore, the standard writing must be:
lock.lock();
try {
while (!conditionSatisfied) {
condition.await();
}
// 执行业务逻辑
} finally {
lock.unlock();
}
You will find that it is the same as the front wait() Best practices are essentially like:
- Get mutually exclusive access
- inspection conditions
- Wait for dissatisfaction
- Recheck the conditions after being awakened
- Execute the real logic at the end
There are many complex-looking APIs in the concurrency, but the bottom-level thinking has not changed.
6. Why await() almost always while instead of if?
This rule and the previous wait() It is the same, and it must continue to be retained.
while (!conditionSatisfied) {
condition.await();
}
Why can't you be lazy to write if?
Because when the thread is woken up, it does not mean that the condition must have been stably met.
These may occur:
1) After being awakened, the lock has to re-compete
When you wake up, it does not mean that you will execute it immediately.
Before you get the lock again, other threads may have changed the conditions.
2) There may be multiple threads being woken up together
When several threads wake up, the first to reacquire the lock may take the available resource. By the time another thread acquires the lock, the condition it was waiting for may already be false.
3) Defensive writing is safer
The most stable logic in concurrency is always:
Don't rush to believe the world after waking up and recheck the conditions.
So keep this pattern dead:
ifa one-time judgmentwhileconditional guard
As long as the conditions are waiting, the priority is used while.
7. The most classic example: use Condition Rewrite the producer - consumer model
Look at the code first.
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedBuffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 5;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public void put(int value) throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) {
notFull.await();
}
queue.offer(value);
System.out.println("生产:" + value);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public int take() throws InterruptedException {
lock.lock();
try {
while (queue.isEmpty()) {
notEmpty.await();
}
int value = queue.poll();
System.out.println("消费:" + value);
notFull.signal();
return value;
} finally {
lock.unlock();
}
}
}
The highlight of this code is that it disassembled the two waiting conditions:
notFull: to producers, etc.notEmpty: to consumers, etc.
This is Condition the core engineering value.
why it is better than wait()/notifyAll() more clear?
Because you can now express very clearly:
- The queue is full, the producer goes
notFullWait here - The queue is empty, consumers go
notEmptyWait here - After producing an element, you only need to wake up consumers who are "waiting for non-empty"
- After consuming an element, you only need to wake up the "waiting non-full" producers
This is better than all threads mixed in a waiting set in the traditional writing method, and then rely on notifyAll() Hard to wake up, much clearer.
And the performance is also more reasonable.
Because you have reduced a lot of unnecessary wake-up and ineffective competition.
Eight, Condition Compare wait()/notify(), where is the strength?
Here you can directly make a summary.
1) Waiting the queue can be split
This is the core advantage.
A Lock can create multiple Condition.
So different types of waiters can enter different conditional queues.
2) The semantics are clearer
you see:
notEmpty.await()notFull.signal()
You can almost understand business intentions directly.
In contrast, simply see wait() / notifyAll(), you often have to go back and read the context, guess what the thread is waiting for.
3) More consistent with the explicit lock system
Now that it has been used before ReentrantLock, then continue to use Condition, will be more neat than half explicit and half of the built-in semantics.
4) More suitable for complex concurrency coordination
When the system has:
- Multiple role threads
- Multiple waiting conditions
- More fine-grained wake-up needs
Condition The advantages will become more and more obvious.
9. When will you continue to use it? wait()/notify(), when to use Condition?
This question is often asked by beginners.
My advice is actually quite straightforward.
1) The scene is simple, the teaching is introduced, and the logic is not complicated: you can use it first synchronized + wait()/notify()
For example:
- Understand the basic principles of thread communication
- Simple one-to-one waiting model
- Concurrent entry practice questions
The advantages of this combination are:
- concept set
- No additional concurrent packets are introduced
- It is suitable to understand the bottom-level thinking first
2) Once the scenario enters the engineering collaboration, especially when there are multiple conditions: give priority to Lock + Condition
For example:
- bounded buffer
- More producers and more consumers
- task state switch
- More complex thread collaboration processes
Because at this time you are more concerned with:
- Readability
- maintainability
- Wake up granularity
- Whether the logical layering is clear
If the system is already complicated, just use a set wait()/notifyAll() The code is more likely to become more and more chaotic.
10. Common pitfalls for beginners
1) Called without holding a lock await() / signal()
This is the same as when you don't have a monitor. wait() / notify() Likewise, it is illegal usage.
You must first lock.lock(), re-operation Condition.
2)await() Do not recheck the conditions after waking up
This is one of the most common pits.
Remember:
Waking up does not mean that the conditions must still hold.
Always prioritize:
while (!条件满足) {
condition.await();
}
3) Forget in finally release lock
One of the biggest risks to an explicit lock is:
- You have to do it yourself
So the template is best to form muscle memory:
lock.lock();
try {
// 业务逻辑
} finally {
lock.unlock();
}
4) put signal() Think of "the other party runs immediately"
No.
signal() Just move the waiting thread from the conditional queue and let it compete for lock.
When it actually continues, it also depends on when the lock is on its turn.
5) The condition design is unclear, and multiple threads use the same one indiscriminately Condition
If you obviously have two completely different waiting logics, but you still stuff them into one Condition, that means writing yourself back to the single queue mode.
Condition The advantage of the splitting and waiting conditions is not to smooth it out by itself.
11. From the design point of view: Condition The significance is not that there are too many APIs, but the concurrent intentions are more clear
Many concurrency tools have learned to the end, and what really widens the level gap is not "will you memorize the method name", but:
Can you express the cooperative relationship between threads clearly.
Condition The design value is precisely here.
It lets you break the original mixed logic into:
- Which locks are responsible for mutual exclusion
- Which condition is responsible for waiting for non-empty
- Which condition is responsible for waiting for the non-full
- Which step to modify the status
- Which step wakes up the right character
When your code can write these relationships clearly, subsequent maintenance, troubleshooting, and expansion will be much easier.
So don't put Condition only as "wait() substitute”.
More precisely:
It is a step in Java concurrency, one step of turning "conditional coordination" from implicit convention to explicit structure.
12. Final summary
If you only take a few sentences in this article, I hope it is the following ones.
1)Condition Be Lock Conditions in the system
await()Correspondwait()signal()Correspondnotify()signalAll()CorrespondnotifyAll()
2) Its biggest advantage is not "can also wait", but "can remove multiple waiting queues"
This allows different types of threads to be managed separately, rather than all crowded in the same monitor waiting set.
3) The basic routine waiting for conditions has not changed
always be:
- Take the lock first
- inspection conditions
- Wait for dissatisfaction
- Recheck the conditions after being awakened
- Satisfy and continue to execute business logic
4)while Ratio if more suitable for conditions waiting
This is a habit that must be developed in concurrency.
5) Simple scenarios can be used first wait()/notify(), complex collaboration is more suitable Condition
Especially when you have multiple waiting conditions, Condition The readability and maintainability will be significantly stronger.
In the next article, I will continue to continue the Java concurrently and then talk about it:
ReadWriteLock What is the problem solved? Why shouldn't "read more and write less" in some scenarios should not use another ordinary Mutex hardtop?
At that time you will find that the Java concurrency tool is not more and more complicated, but is constantly refined around a core issue:
Between different threads, how to cooperate safely and effectively as much as possible.