Java ReentrantLock Class - Explicitly Acquiring a Lock
Explicitly Acquiring a Lock - ReentrantLock Class
public void lock()
public void unlock()
Synchronization with a synchronized block is called an “implicit lock” because application developers do not have to be aware of acquiring or releasing the lock. Conversely, there are cases where you want to explicitly lock or unlock through methods. In such cases, use the ReentrantLock class in the java.util.concurrent.locks package.
In the ReentrantLock class, after explicitly locking with the lock method, you must release it with the unlock method.
The following rewrites the example using the synchronized modifier, the increment method, with the ReentrantLock class.
LockSample.java
package com.devkuma.basic.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockSample {
private int count;
private final Lock lock = new ReentrantLock();
public static void main(String[] args) {
LockSample ls = new LockSample();
ls.execute();
}
public void execute() {
final int THREAD_MAX = 300000;
Thread[] ts = new Thread[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++) {
ts[i] = new Thread(new MyThread(this));
ts[i].start();
}
for (int i = 0; i < THREAD_MAX; i++) {
try {
ts[i].join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println(count);
}
public void increment() {
lock.lock();
try {
this.count++;
} finally {
lock.unlock();
}
}
private static class MyThread implements Runnable {
private LockSample _counter;
public MyThread(LockSample counter) {
this._counter = counter;
}
@Override
public void run() {
_counter.increment();
}
}
}
Result:
300000
When using the lock method in the ReentrantLock class, wrap the code immediately after it in a try block. This is to guarantee that the unlock method is called in the finally clause even if an unexpected exception occurs during processing.