Created
October 29, 2014 19:31
-
-
Save stepancheg/e4595d628d1dad4bd28d to your computer and use it in GitHub Desktop.
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
public class MutexWithData<A> { | |
private final ReentrantLock lock = new ReentrantLock(); | |
private final A data; | |
public MutexWithData(A data) { | |
this.data = data; | |
} | |
public Guard lock() { | |
lock.lock(); | |
return new Guard(); | |
} | |
public class Guard { | |
private Guard() { | |
} | |
public A getData() { | |
return data; | |
} | |
public void unlock() { | |
lock.unlock(); | |
} | |
} | |
public <T> T withLock(Function<A, T> op) { | |
Guard guard = lock(); | |
try { | |
return op.apply(guard.getData()); | |
} finally { | |
guard.unlock(); | |
} | |
} | |
public void withLockNr(Consumer<A> op) { | |
withLock(a -> { | |
op.accept(a); | |
return null; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment