Last active
December 31, 2015 00:39
-
-
Save kofemann/7908629 to your computer and use it in GitHub Desktop.
Locks in try-with-resource semantics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.locks.Condition; | |
import java.util.concurrent.locks.Lock; | |
/** | |
* A utility class to use locks with try-with-resource semantics: | |
* <pre> | |
* import static Locks.withLock; | |
* import Locks.AutoLock; | |
* | |
* Lock lock = ...; | |
* try (AutoLock l = withLock(lock)) { | |
* // access the locked resource | |
* } | |
* </pre> | |
*/ | |
public final class Locks { | |
private Locks() { | |
} | |
public static AutoLock withLock(Lock lock) { | |
lock.lock(); | |
return new AutoLock(lock); | |
} | |
public final static class AutoLock implements AutoCloseable, Lock { | |
private final Lock inner; | |
AutoLock(Lock lock) { | |
this.inner = lock; | |
} | |
@Override | |
public void lock() { | |
inner.lock(); | |
} | |
@Override | |
public void lockInterruptibly() throws InterruptedException { | |
inner.lockInterruptibly(); | |
} | |
@Override | |
public boolean tryLock() { | |
return inner.tryLock(); | |
} | |
@Override | |
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { | |
return inner.tryLock(time, unit); | |
} | |
@Override | |
public void unlock() { | |
inner.unlock(); | |
} | |
@Override | |
public Condition newCondition() { | |
return inner.newCondition(); | |
} | |
@Override | |
public void close() { | |
inner.unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment