📜  java reentrantlock - Java (1)

📅  最后修改于: 2023-12-03 15:31:31.865000             🧑  作者: Mango

Java ReentrantLock

Java ReentrantLock is a class that provides a mutual exclusion synchronization mechanism. It is a lock that can be acquired multiple times by the same thread without causing a deadlock. It is used to protect critical sections of code that should only be accessed by one thread at a time.

How to use ReentrantLock

To use ReentrantLock, you first need to create an instance of it:

ReentrantLock lock = new ReentrantLock();

To acquire the lock, use the lock() method:

lock.lock();

This will block the current thread until the lock is available. Once the lock is acquired, the thread can proceed to access the critical section:

// critical section of code

To release the lock, use the unlock() method:

lock.unlock();

This will release the lock, allowing other threads to acquire it.

ReentrantLock vs synchronized

Both ReentrantLock and synchronized provide a way to protect critical sections of code. However, ReentrantLock provides additional features that are not available with synchronized, such as:

  • The ability to interrupt a thread that is waiting for the lock using the lockInterruptibly() method.
  • The ability to specify a timeout when acquiring the lock using the tryLock(long timeout, TimeUnit unit) method.
  • The ability to acquire the lock multiple times by the same thread using the lock() method. This is called reentrant behavior.
Example

Here is an example of using ReentrantLock to protect a critical section of code:

import java.util.concurrent.locks.ReentrantLock;

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

    public void criticalSection() {
        lock.lock();
        try {
            // critical section of code
        } finally {
            lock.unlock();
        }
    }
}
Conclusion

ReentrantLock is a powerful tool for synchronizing access to critical sections of code. It provides features that are not available with synchronized, such as interruptible locking and reentrant behavior. However, it is also more complex to use than synchronized, so it should only be used when necessary.