#477 Code Review of Waiting for a Condition with Lock and Condition
Perform a review: is everything correct here?
class Scratch {
private static final Logger log = getLogger(Scratch.class);
private static volatile boolean ready = false;
private static final Lock rLock = new ReentrantLock();
private static final Condition readyCondition = rLock.newCondition();
private static void waitAndLog() {
try {
rLock.lock();
log.info("rLock acquired, ready: {}", ready);
if (!ready)
readyCondition.await();
log.info("ready was awaited: {}", ready);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
finally {
rLock.unlock();
}
}
public static void main(String[] args) {
new Thread(Scratch::waitAndLog).start();
try {
rLock.lock();
ready = true;
log.info("signal about ready");
readyCondition.signal();
}
finally {
rLock.unlock();
}
}
}Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor