Auto Close Resources: A Lock Wrapper in Java that Allows AutoCloseable (Try-With-Resources)


We can use the following Java Wrapper for Lock so that we can Try-With-Resources to Auto Close the Lock:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
    }
}
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
        }
    }
}
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) —

GD Star Rating
loading...
197 words
Last Post: Teaching Kids Programming - Multiples of 3 and 7
Next Post: Teaching Kids Programming - Group Integers

The Permanent URL is: Auto Close Resources: A Lock Wrapper in Java that Allows AutoCloseable (Try-With-Resources)

Leave a Reply