We can use the following Java Wrapper for Lock so that we can Try-With-Resources to Auto Close the Lock:
public final class ALock implements AutoCloseable {
private final Lock lock;
public ALock(Lock l) {
this.lock = l;
}
public final ALock lock() {
this.lock.lock();
return this;
}
public final void close() {
this.lock.unlock();
}
}
For example, we can do this:
package helloacm.com
public class LockWrapperTesting {
public static void main(String[] args) {
var value = 1.0;
var lock = new ReentrantLock();
var wLock = new ALock(lock);
try (var l = wLock.lock()) {
value ++;
System.out.println("Hello " + value);
}
}
}
This Java code prints “Hello 2.0” to the console. We use a ReentrantLock to enter the critical code block where we increment the value.
The Lock will be automatically unlocked after the try {} block.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Multiples of 3 and 7
Next Post: Teaching Kids Programming - Group Integers