Skip to content

Instantly share code, notes, and snippets.

Last active November 6, 2019 15:39
What would you like to do?
Allows using a java.util.concurrent.lock in a Java try-with-resources statement
import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.concurrent.locks.Lock;
* Allows using a {@link java.util.concurrent.locks.Lock} with a try with resources, e.g.:
* <code> try (LockAsAutoCloseable locked = LockAsAutoCloseable.lock(lock)) { ... } </code> .
public class LockAsAutoCloseable implements AutoCloseable {
protected final Lock lock;
protected LockAsAutoCloseable(Lock lock) {
this.lock = lock;
* Acquires a lock on the given lock and allows using it the try-with-resources way. For example:
* <code> try (LockAsAutoCloseable locked = LockAsAutoCloseable.lock(lock)) { ... } </code> .
* Always use in try-with-resource statement.
public static LockAsAutoCloseable lock(@Nonnull Lock lock) {
return new LockAsAutoCloseable(lock);
/** Unlocks the lock. */
public void close() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment