std::unique_lock<> for Java

Motivation

  • A high-level synchronized keyword
  • Java Concurrent API (java.util.concurrent.*)
  • do some work in a locked/reentrant area;
  • based on the result of this work, do some other work outside lock.
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;
class Test {
private final Lock myLock = new ReentrantLock();
private AnyYourStatefulObject myState;

private void dangerousWork() throws IOException {
// do something with the state
// which also might cause an IO exception for example
myState.load...
}

private void doSomethingOutside(Object resOfTheDangerousWork){
// doesn't matter what we do here
// but we would like to do it without any lock
}

void myReentrantFunction() {

myLock.lock();
boolean unlocked = false;
try {
// do something inside a restricted area
dangerousWork();
// we can't release lock yet,
// because the state might be changed from another thread
if(myState.hasDoneSomethingWeExpect()) {
// we have to save a local copy of the result
Object someStateResult = myState.getSomeStateResult();
myLock.unlock();
unlocked = true;
// Doing something outside lock
doSomethingOutside(someStateResult);

}
else {
// do something without unlocking
myState.clearIt();
}
}
finally {
if(!unlocked)
myLock.unlock();
}

}
}

Solving

void myReentrantFunction() {

try(final var monitor = UniqueLockMonitor.lockAndMonitor(myLock)) {
dangerousWork();
if (myState.hasDoneSomethingWeExpect()) {
Object someStateResult = myState.getSomeStateResult();
monitor.unlock();
doSomethingOutside(someStateResult);
} else {
myState.clearIt();
}
}
}

--

--

Software Developer & Architect

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store