In the previous article, we made it clear about thread communication:

  • wait() / notify() / notifyAll() What are you doing
  • Why threads are sometimes not "snatching locks", but "waiting conditions"
  • Why thread communication must communicate with synchronized use with
  • How to cooperate in the producer-consumer model of waiting and awakening

But when you continue to learn Java concurrency, you will soon encounter another problem:

Since synchronized It can be locked, why does Java still provide Lock This explicit lock mechanism?

Many beginners see ReentrantLock There are some doubts:

  • Isn't this also locked?
  • and synchronized What is the essential difference?
  • Who should give priority to development?
  • lock()、unlock()、tryLock()、lockInterruptibly() Which scenarios are suitable for?
  • Condition and learned earlier wait() / notify() What's the relationship?

This article, I will connect this line completely.

You can understand it as:

The first step from "With Built-in Lock" to "Will Select Lock Tool".

This article focuses on 6 things:

  1. synchronized and Lock what is the relationship
  2. ReentrantLock Why is it called "reentry lock"?
  3. What are the abilities of explicit locks more than built-in locks?
  4. tryLock(), can be interrupted, locked, and fair lock can be solved.
  5. Condition Why compare wait() / notify() More flexible
  6. When should it be used in actual development synchronized, when to consider ReentrantLock

You can read this article thoroughly, and then learn it later:

  • ReadWriteLock
  • StampedLock
  • Condition
  • Concurrency Control in Thread Pool
  • Advanced concurrency tools under the AQS system

will be much smoother.


First, give conclusions: Lock Not everything, but giving you stronger control

When many people just learn concurrency, it is easy to understand the problem as:

  • synchronized Is old
  • Lock New
  • So Lock Must be more advanced and should be preferred

This is actually not right.

A more accurate understanding should be:

1)synchronized Is the synchronization mechanism built in Java

It is simple, direct and semantically stable.

You just write:

synchronized (lock) {
    // 临界区代码
}

can complete mutual exclusion control.

2)Lock is an explicit lock interface provided by concurrent packets

You can decide when to acquire and release the lock, whether to try acquiring it without waiting, whether a waiting thread can respond to an interrupt, and whether to use a fair queue.

So you can remember this first:

  • synchronized: Enough, simple, suitable for most basic synchronization scenarios
  • Lock: More flexible, suitable for when you need fine control

That is, Lock The value is not "can be locked", but "can control the locking behavior in more detail".


2. What is re-entry lock?

ReentrantLock The most important word in this class name is Reentrant (Reentrant).

So what is reentrant?

means:

If the same thread has already got the lock, it can get the lock again without getting stuck.

For example:

public class Demo {
    private final ReentrantLock lock = new ReentrantLock();

    public void methodA() {
        lock.lock();
        try {
            System.out.println("进入 methodA");
            methodB();
        } finally {
            lock.unlock();
        }
    }

    public void methodB() {
        lock.lock();
        try {
            System.out.println("进入 methodB");
        } finally {
            lock.unlock();
        }
    }
}

When the same thread enters first methodA(), call again methodB() It will successfully get the same lock again.

What happens if the lock is not reentered?

That thread will block itself:

  • The lock was already held when it first came in
  • Request the same lock for the second time
  • Locks do not allow repeated entry
  • So the thread is always waiting for itself to release

This is obviously unreasonable.

So whether synchronized or ReentrantLock, which essentially supports re-entry.

This is also the reason why many recursive calls and nested sync calls can work normally.


Three synchronized and ReentrantLock What is the commonality?

Start with what the approaches have in common.

They can all do these things:

  • Ensure that only one thread enters the critical section at the same time
  • Protect shared data and avoid concurrent write chaos
  • Establish a synchronization relationship between threads
  • Support re-entry

That is, At the "most basic mutual exclusion" level, they both solve the problem.

If your needs are just:

  • Only one thread is allowed to execute a method at the same time
  • Several lines of shared variable modification need to be protected
  • There are no timeouts, disconnectability, and fairness requirements

That often synchronized It's totally enough.

So don't put ReentrantLock Deification into "must replace" synchronized standard answer".


Four, that ReentrantLock What is more?

This is the real focus of this article.

ReentrantLock Compare synchronized, the biggest advantage is not "can be locked", but I have given you more control methods.

Mainly look at the following categories.

1) Can be explicitly locked and released explicitly

lock.lock();
try {
    // 临界区
} finally {
    lock.unlock();
}

You will find that it is not like synchronized That is automatically released by the code block boundary, but is controlled by yourself.

The benefits of this are:

  • Locks are more flexible
  • Can organize logic across multiple code snippets
  • More suitable for some complex process control

But the price is also obvious:

If you forget unlock(), there will be a big problem.

So ReentrantLock almost always cooperate try/finally use.

2) You can try to get locks instead of dead etc.

This is tryLock() value.

if (lock.tryLock()) {
    try {
        System.out.println("拿到锁,执行业务");
    } finally {
        lock.unlock();
    }
} else {
    System.out.println("没拿到锁,走降级逻辑");
}

This is especially useful in many scenarios, such as:

  • Don't want to block threads for a long time
  • Return directly without grabbing the lock
  • Want to downgrade, retry, skip the current task
  • Avoid multiple threads stacking dead on a hot resource for a long time

synchronized There is no such semantics of "try it, if it doesn't work".

3) You can set a timeout waiting

if (lock.tryLock(2, TimeUnit.SECONDS)) {
    try {
        System.out.println("2 秒内成功拿到锁");
    } finally {
        lock.unlock();
    }
} else {
    System.out.println("等了 2 秒还没拿到");
}

This ability is also very practical.

Because in many real systems, the most fearful thing is not that they can't grab the lock, but:

The thread is stupid indefinitely, etc., and finally drags the throughput, response time, and call chain to death.

If there is a timeout, you can do a more secure strategic control.

4) Can respond to interrupts

This is lockInterruptibly() meaning.

lock.lockInterruptibly();

It says:

If the thread is interrupted while waiting for the lock, then don't continue to wait and respond directly to the interrupt.

This is important for canceling tasks, stop threads, and timeout controls.

synchronized While waiting to enter the monitor, the interrupt support is not so flexible.

5) Fair lock or unfair lock can be selected

Structure ReentrantLock can be written like this:

ReentrantLock fairLock = new ReentrantLock(true);

true Indicates a fair lock.

Fair lock means:

A fair lock generally serves threads in the order they started waiting, giving earlier arrivals a better chance of acquiring it first.

The default is a nonfair lock. It usually offers higher throughput, though some threads may wait longer.

So you can understand this:

  • Fair Lock: More on the queuing order
  • Unfair lock: more about performance and throughput

However, it should be noted that fairness is not "absolute fair", but try to arrange according to the rules.


5. Why is explicit lock more suitable for complex concurrency control?

Because of the concurrency problems in the real world, many of them are not just as simple as "surrounding a piece of code and adding a lock".

For example:

  • A thread is only willing to wait 500ms
  • A background task can be canceled
  • When a resource can't be grabbed, you have to go to the downgrade logic
  • A certain type of thread needs a more stable queuing order
  • A group of waiting conditions needs to be managed separately, instead of all threads mixed in a waiting queue

At this moment ReentrantLock The advantages come out.

It's more like:

Change the "lock" from syntactic sugar to an object that can orchestrates the strategy.

This is why explicit locks are particularly common in some frameworks, middleware, and concurrent containers.


Six, Condition what is it? why it is better than wait() / notify() More flexible?

If you have studied the previous article, you will know:

  • wait(): thread waits
  • notify(): wake up one
  • notifyAll(): wake up all

But this mechanism has obvious limitations:

The waiting threads on the same lock object are crowded in a waiting set by default.

Often this is not detailed enough.

For example, in the producer-consumer scenario, there are often two types of conditions:

  • If the queue is dissatisfied, the producers can continue to play
  • The queue is not empty, consumers can continue to take

If all threads are in a waiting queue, you will often encounter:

  • Wake up the thread that shouldn't wake up
  • After waking up, I found that the conditions were not met
  • Continue to sleep again

Efficiency is not good.

And Condition The core value is:

A lock can associate multiple condition queues.

Schematic writing:

private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();

This way:

  • Producers can wait notFull
  • Consumers can wait notEmpty

The waiting and awakening of each other is more precise.

This is where explicit locks are particularly valuable in complex thread coordination.


7. Look at one Condition Producer - Consumer Examples

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MessageQueue {
    private final Queue<String> 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(String message) throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() == capacity) {
                notFull.await();
            }

            queue.offer(message);
            System.out.println("生产消息:" + message);

            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public String take() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                notEmpty.await();
            }

            String message = queue.poll();
            System.out.println("消费消息:" + message);

            notFull.signal();
            return message;
        } finally {
            lock.unlock();
        }
    }
}

This example is especially suitable for you to experience Condition Advantages:

  • When full, only let the producers wait notFull
  • When it is empty, only let consumers wait notEmpty
  • After adding the data, only wake up the "waiting for consumption" thread
  • After taking the data, only wake up the "waiting for production" thread

Compare to all threads wait() / notifyAll(), this set of logic is clearer, and it is closer to the real business needs.


Eight, use ReentrantLock What are the easiest pits to step on?

You'd better take a serious look at this part, because many of the problems in the actual development lie in this.

1) Forget in finally release lock

Wrong spelling:

lock.lock();
doSomething();
lock.unlock();

If doSomething() throw an exception in the middle, unlock() may not be executed at all.

Correct writing:

lock.lock();
try {
    doSomething();
} finally {
    lock.unlock();
}

This is almost a hard rule.

2) If you get the lock several times, you have to release it several times

Because it is reentrant lock.

If the same thread continues lock() After twice, it must also correspond unlock() The lock will be released twice.

3)tryLock() Don't forget to release after success

Some people think that "this is an attempt to obtain, not necessarily successful", but after the result is successful, it is forgotten unlock().

4)await() / signal() It must also be called while holding the lock

and wait() / notify() the same, Condition It's not just random.

They must be used if they already hold the corresponding lock, otherwise they will throw exceptions.

5) When waiting for conditions, still use while, don't write it if

like this:

while (queue.isEmpty()) {
    notEmpty.await();
}

Don't make it easier to write:

if (queue.isEmpty()) {
    notEmpty.await();
}

Why?

Because after the thread is woken up, it does not mean that the conditions must still be satisfied. Possible:

  • False wake-up
  • Some other threads changed the state first
  • After multi-threaded competition, the conditions are invalid again

So the standard way is:

Wake up and recheck the conditions.


9. In actual development, who should give priority to using it?

This is the question that many people are most concerned about.

I give you a very practical judgment principle.

be preferred synchronized The scene

If you just:

  • Protect a simple shared variable
  • Synchronize a method or a small critical section
  • No timeout required, interruptible, fairness
  • Multiple conditional queues are not required

Then use first synchronized Very reasonable.

The reason is simple:

  • code is shorter
  • The error surface is smaller
  • It is not easy to forget to release the lock
  • more direct semantics

Consider ReentrantLock The scene

If you need:

  • try to get the lock (tryLock())
  • Timeout to get lock
  • Respond to interrupt while waiting for lock
  • more flexible conditional queues (Condition)
  • fair lock control
  • More complex concurrency orchestration

That ReentrantLock more suitable.

So don't understand the choice as "who is more advanced", but to understand it as:

Who is more suitable for the current problem.


10. One more step forward: After this study, what kind of picture will be formed in your mind?

At this point, you should have stringed together the most basic set of tools in Java concurrency:

Level 1: Mutual Exclusion

  • synchronized
  • Lock

The solution is: who can enter the critical section at the same time.

Level 2: Conditional Coordination

  • wait() / notify()
  • Condition.await() / signal()

The solution is: when to wait and when to continue.

Tier 3: More complex concurrency

You will continue to learn later:

  • ReadWriteLock
  • Semaphore
  • CountDownLatch
  • CyclicBarrier
  • BlockingQueue
  • Thread Pool

These tools are essentially doing one thing:

Express the cooperation rules between multi-threads more clearly.

In other words, concurrent programming is not just "locking", but designing:

  • How resources are mutually exclusive
  • How to wait for the conditions
  • How to coordinate the thread
  • How to take risks

Finally, a summary

In today's article, you can write down the core into the following sentences.

1)synchronized and ReentrantLock mutually exclusive

In terms of the most basic locking capabilities, they can all protect shared resources.

2)ReentrantLock The value of "more control"

It is not simply to "recreate a lock", but to provide:

  • try to lock
  • Timed out
  • can be interrupted
  • Fair lock
  • multi-condition queue

3)Condition Is better than wait() / notify() More fine-grained conditional coordination tools

Especially in multiple conditions, it will be obviously clearer.

4) Simple scenes are over-designed, and complex scenes are hard to support only use synchronized

The concurrency tool has no "unique correct answer", only "whether to meet the current needs".


If you've just learned this, I suggest you continue to follow this line in the next step:

  1. ReentrantLock and synchronized underlying differences
  2. ReadWriteLock Why "Read more and write less"
  3. BlockingQueue How to encapsulate the producer-consumer model
  4. Why Thread Pool is more suitable for real projects than manually creating threads

If you want, I can continue to write the next article:

Java from Beginner to Advanced (18): ReadWriteLock — Why should read-heavy workloads use more than a single mutex?