Skip to content

Instantly share code, notes, and snippets.

@stoerr
Last active November 6, 2019 15:39
Show Gist options
  • Save stoerr/cc0394c7d3d5de4c20233570183004cc to your computer and use it in GitHub Desktop.
Save stoerr/cc0394c7d3d5de4c20233570183004cc to your computer and use it in GitHub Desktop.
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> .
*/
@SuppressWarnings("LockAcquiredButNotSafelyReleased")
public class LockAsAutoCloseable implements AutoCloseable {
protected final Lock lock;
protected LockAsAutoCloseable(Lock lock) {
Objects.requireNonNull(lock);
this.lock = lock;
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.
*/
@Nonnull
public static LockAsAutoCloseable lock(@Nonnull Lock lock) {
return new LockAsAutoCloseable(lock);
}
/** Unlocks the lock. */
@Override
public void close() {
lock.unlock();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment