In the previous article, we took the thread communication open and explained it clearly:
- Thread synchronization solves the "don't change at the same time"
- Thread communication solves the solution to "Wait before the conditions arrive, and continue when the conditions are over"
wait()/notify()why must andsynchronizedUse together- Why is it recommended to wait for conditions?
whileinstead ofif - Producer-consumer model is a classic training ground for concurrent entry
But when I learn this, a lot of people will quickly come up with a new problem:
Since Java already has synchronized Now, why do you have to learn later? Lock?
And when you look at the code, you may be more puzzled:
synchronizedIt can already be guaranteed to be mutually exclusive, why do you have to manuallylock()/unlock()?ReentrantLockWhere is the "advanced"?- What is reentrant? it and
synchronizedWhat do you have in common? - What does it mean to be fair lock, interrupt lock, and try to add lock?
- In real development, when should it be used
synchronized, when is it better toReentrantLock?
Behind these questions, they are essentially asking:
Why does the concurrency control of Java keep the "built-in lock" and "explicit lock" two solutions at the same time?
This article will explain this.
I would like to focus on answering 6 questions:
LockWhat is the interface to solveReentrantLockandsynchronizedcommonalities and differences- What is "reentrant" and why it is important
lock()、unlock()、tryLock()、lockInterruptibly()What scenarios are suitable for- How to understand fair locks and unfair locks
- Which pitfalls should beginners watch for?
You can read this article thoroughly, and then learn it later:
ConditionReadWriteLockStampedLock- Lock designs in concurrent containers and Thread Pool
will be much smoother.
First, the conclusion: Lock not for substitution synchronized, but to provide more controllable locking capabilities
Many people learn for the first time Lock, will subconsciously understand it as "more advanced version synchronized".
This understanding is not wrong, but not accurate enough.
The better statement is:
synchronized It is a built-in synchronization mechanism in the Java language, with simple, sufficient and stable syntax; Lock It is an explicit lock scheme provided by concurrent packets, focusing on more flexible and controllable.
They all solve mutually exclusive problems, but the design goals are not exactly the same.
1)synchronized features that are simple
You write keywords and JVM will help you complete:
- Get the lock before entering the synchronization area
- Automatically release locks after leaving the sync area
- It is automatically released even if there is an exception
So it is especially suitable for:
- Getting Started
- Logic Critical Zone Protection
- Scenarios with clear lock range
2)Lock feature explicit control
Use Lock When you need to write yourself:
- When to lock
- when to release the lock
- Whether to try to lock
- Whether to respond to interrupts
- Whether to use a fair policy
- Whether to split multiple waiting conditions
It sounds more troublesome, but it also means you gain more control.
So Lock Instead of "writing complex simple things", it's not:
When concurrent control needs ratio synchronized When more complex, give you more engineering means.
Second, let's look at the most basic writing: ReentrantLock How to use it?
Don't rush to compare, first see the most basic usage method.
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
The most important thing in this writing is two things:
1) first lock() into key areas
This and synchronized The goal is consistent:
- Only one thread is allowed to enter the critical area at the same time
2) Must be in finally In unlock()
This is one of the most important habits of using explicit locks.
because of synchronized different, Lock It will not help you automatically release the lock.
If you quit abnormally in the middle, but forget unlock(), then the other threads may be stuck all the time.
So, first, let this rule die:
lock() Almost always with one try/finally.
3. What is reentrant? Why ReentrantLock Is it in this name?
The word "reentry" sounds a bit abstract, but the meaning is not difficult.
It refers to:
If the same thread has already got a lock, it will not be blocked by itself when it requests the lock again.
Take an example first.
public class Demo {
public synchronized void methodA() {
methodB();
}
public synchronized void methodB() {
System.out.println("methodB 执行");
}
}
here methodA() Called methodB(), and both methods are added synchronized.
What happens if the lock is not reentered?
- The current thread enters
methodA(), get the lock - Implemented to
methodB()apply for the same lock again - If reentry is not allowed, the thread will get stuck on itself
Java obviously can't be designed like this.
So whether synchronized or ReentrantLock, which essentially supports re-entry.
Why is reentrance important?
Because in real code, method calls are often nested layer by layer:
- One synchronization method to another synchronization method
- Subclass methods call parent class synchronization logic
- Business logic split into multiple internal aids
If the lock cannot be re-entered, many normal program structures will have problems.
Therefore, "reentry" is not the icing on the cake, but the basic ability in the design of concurrent locks.
Four, ReentrantLock and synchronized What are the things in common?
Don't just look at the difference, they actually have a lot in common.
1) It can guarantee mutually exclusive access
At the same time, only one thread can enter the critical area.
2) Both support re-entry
After the same thread gets the lock, you can enter the code protected by the same lock again.
3) It can be used to protect shared resources
For example:
- Counter
- Stock
- Order Status
- buffer zone
- Account Balance
4) Neither is "the more the better"
As long as a lock is involved, it means:
- Waiting
- Have a competition
- May affect throughput
So whatever it is used, the essential goal is still:
Replace correctness and consistency with acceptable concurrency costs.
5. Why do you still need ReentrantLock? because it provides synchronized A few abilities that are not good at
This is the core part of this article.
1) You can try to add locks instead of infinite deaths, etc.
synchronized The features are:
- or get locked in
- Either you can't get it, just keep waiting
But ReentrantLock You can write like this:
if (lock.tryLock()) {
try {
// 拿到锁再执行
} finally {
lock.unlock();
}
} else {
System.out.println("没有拿到锁,先做别的事");
}
This is very practical in some businesses.
For example:
- Don't want to block threads for a long time
- Want to fail quickly, try again later
- Some tasks can't be locked and give up directly
These needs are synchronized Not flexible enough.
2) Can wait for the lock in response to the interrupt
Sometimes when threads are waiting for a lock, they should not wait stupidly to the end.
If the outside has decided to cancel this task, and you want the thread to not continue to wait, you need to "interrupt and lock".
lock.lockInterruptibly();
This means:
- Get the lock if it is available
- If it is currently interrupted while waiting for a lock, stop waiting and throw an exception
This ability in:
- Task cancellation
- Timeout control
- Complex task coordination in Thread Pool
It is very practical.
And synchronized In the matter of waiting to enter the monitor, the control is not so fine.
3) Fair locks or unfair locks can be specified
ReentrantLock can be created like this:
ReentrantLock fairLock = new ReentrantLock(true);
Here true Indicates a fair lock.
The general meaning of a fair lock is:
Try to allocate locks in order of waiting time in sequence.
Unfair locks, on the other hand, emphasize throughput and allow the phenomenon of "jumping in the queue" to be more likely to occur.
Generally speaking:
- Fair lock is more about order
- Unfair locks usually have a higher throughput
synchronized This layer of control is not so explicit.
4) Can match multiple Condition Do finer thread coordination
We talked about the previous one wait() / notify().
But they have a limitation:
- Waiting queues are managed based on object monitors
- The condition management on the same lock is not fine enough
And ReentrantLock Can cooperate Condition, make different threads and other different conditions.
For example:
- Producers, etc. "The queue is not full"
- "The queue is not empty"
This will be more simple notifyAll() Clearer and easier to scale.
This is also why many slightly more complicated concurrent collaboration scenarios will gradually start from synchronized transition to Lock + Condition.
6. How to understand fair locks and unfair locks?
This is ReentrantLock There is a point that is easy to ask, but many tutorials are too abstract.
1) Fair lock: first come first service
You can think of it in line to buy tickets.
- Who will line up first
- Who gets the service first
The advantages of this strategy are:
- More fair
- It's not easy to make some threads hungry for a long time
The disadvantages are:
- Scheduling is more conservative
- Suffering is usually not that high
2) Unfair lock: whoever grabs it will go first
It's more like grabbing an elevator.
Although someone has waited for a while, if a newly arrived thread is lucky, it may also get the lock first.
The advantages are:
- Performance is usually better
- Higher swallows
The disadvantages are:
- Some threads may theoretically wait longer
How to choose in the project?
In most general business:
- Default unfair lock is enough
Only if you express concern:
- Waiting order
- thread hungry
- It is unreasonable for some tasks to fail to get locks for a long time
Only when you need to carefully evaluate the fair lock.
Don't think of fair locks as "a more advanced default option".
It's just another trade-off.
Seven, tryLock() Why is it so practical? It allows you to change "blocking" to "decision"
This is ReentrantLock Compare synchronized Very representative point.
Take a simple example:
public void doTask() {
if (lock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + " 拿到锁,开始执行");
} finally {
lock.unlock();
}
} else {
System.out.println(Thread.currentThread().getName() + " 没拿到锁,稍后再试");
}
}
This code expresses:
- Execute the lock
- If you can't get the lock, don't block it, go to other logic first
This idea is very valuable in many real scenes, such as:
- Scheduled tasks do not want to repeat
- When a resource is being occupied, the current request will directly return to "try again later"
- Some background cleaning tasks can't get the lock and skip this round
So tryLock() It's not just "a one more API", but:
You can turn "waiting locks" from passively blocking to active decision-making.
Eight, lockInterruptibly() What scenario is suitable for?
Many beginners in this API will skip the past, but it reflects the engineering value of explicit locks.
Look at the background of the problem first.
When some threads are waiting for a lock, if the system no longer needs it to continue to wait, it should exit as soon as possible.
For example:
- User canceled request
- The upper-level task has timed out
- Thread Pool ready to close
- The current thread is just a candidate task, it is not worth waiting for
At this time, if you let the thread wait infinitely for the lock, it is not very reasonable.
lockInterruptibly() The value is:
Threads can respond to interrupt signals while waiting for locks.
This means that the system can cancel and clean up tasks more proactively, rather than letting the thread get stuck there.
For beginners, it is enough to remember this sentence first:
lock()More suitable for "must get the lock and then dry"lockInterruptibly()More suitable for "allowing to be canceled while waiting"
ninth, synchronized and ReentrantLock How to choose?
This is the most practical question.
My advice is straightforward:
1) If it is only the basic mutual exclusion, the priority is given synchronized
For example:
- protect a counter
- Simple modification to protect a shared collection
- Concurrent mutual exclusion of an instance method
- Concurrent teaching and basic exercises
The reason is simple:
- Syntax is short
- good readability
- It is not easy to forget to release the lock
- stable enough
2) If you clearly need more flexible control, then consider ReentrantLock
For example you need:
- try to get the lock
- Respond to interrupt when locking
- Specify a fair policy
- Multiple condition queues
- More complex concurrency coordination logic
At this moment ReentrantLock The advantages are truly reflected.
3) Don't misunderstand "more flexible" as "should default to use"
Some people learn ReentrantLock After that, I will feel that it is more professional, so I can't wait to change all synchronizations to explicit locks.
This is usually not necessary.
Because of its flexibility, it is accompanied by:
- More template code
- The risk of forgetting to release locks is higher
- The mental burden is heavier
So the most secure principle is usually:
simple mutual exclusion synchronized, complex control ReentrantLock.
10. A simple comparative proportion: what are the two ways of writing?
Use synchronized
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
Features:
- concise writing
- not easy to make mistakes
- Locks released by JVM
Use ReentrantLock
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
Features:
- more verbose
- But there is more room for expansion in the future
- can be further added
tryLock(), fair lock,Conditionabilities
If currently only "protected" count++", the former is usually enough.
If there is more complex waiting control later, the latter will be more scalable.
11. Eight common pitfalls for beginners
1)lock() Forget later unlock()
This is the most classic and dangerous mistake.
Once the lock is forgotten, other threads may block for a long time.
2) Don't put unlock() put in finally
If an abnormality is thrown in the middle, the lock may leak.
3) put ReentrantLock as "the default is more advanced so it must be used"
No.
Many simple scenarios synchronized more suitable.
4) Misunderstandings about fair locks
Fair locks are not "more advanced", but "more on the order".
Usually a part of the throughput is sacrificed.
5) see tryLock() Just use everywhere
If the business is inherently the lock, forcibly tryLock() Instead, it will convolve the logic.
6) The premise of forgetting that reentrant is "same thread"
Reentrancy lets the thread that already holds the lock acquire it again. Other threads still have to wait.
7) Confuse "Lock object is consistent" and "code position close"
Whether it is synchronized Still is ReentrantLock, the prerequisites that really generate mutual exclusion are:
- Multiple threads compete for the same lock
8) I don't know why I don't use it synchronized
If you can't answer "Why do you have to use it here? ReentrantLock”, which often shows that this is not necessarily really needed here.
12. How should you establish a correct understanding of explicit locks?
If you are now from synchronized transition to Lock, I suggest understanding in this order.
Step 1: First admit that both can be mutually exclusive
Don't put ReentrantLock Deify into something completely different.
It is also lock first.
Step 2: Look at its extra control ability
Focus on these issues:
- Can you try to get a lock
- Can you respond to interrupts?
- Can you specify a fair policy?
- Can you split different conditions and wait for the queue?
This is its value.
Step 3: Finally, decide whether it is worth introducing
Not every concurrent code is worth using more complex tools.
The more important thing in the project is not "there will be more APIs", but:
Solve the current problem with the most suitable and stable solution.
13. Final summary: ReentrantLock value, not a replacement synchronized, but give more operation space to complex and concurrent scenes
If I sum it up in one sentence, I would say:
synchronized More like the default built-in lock, suitable for simple and direct mutual exclusion; ReentrantLock More like explicit concurrency tools, suitable for scenarios that require finer controls.
What you should really take away is the following core understandings:
1)ReentrantLock and synchronized Support mutual exclusion and reentrant
So they are not two sets of worlds that are completely separated.
2) The meaning of reentrant is that the same thread can enter the same lock protection code again after getting the lock.
This ensures that nested calls do not lock itself.
3)ReentrantLock The advantage is that it provides stronger control
For example:
tryLock()lockInterruptibly()- Fair lock
- follow-up
Condition
4) The most important discipline of the explicit lock is lock() must be later try/finally
Otherwise, it is very easy to cause accidents.
5) Don't pursue "who is more advanced" when choosing a model, but look at "who is more suitable for the current complexity"
simple mutual exclusion synchronized, complex control reuse ReentrantLock, which is usually a very stable idea.
You’ve now gone beyond using Java’s built-in locks and learned how to use explicit locks when you need finer control.
Next, the most natural continuation direction is:
Condition What is it? Why do you have wait() / notify(), Java also provides the mechanism of conditional queue?