Skip to content

Instantly share code, notes, and snippets.

@nikkatsa
Created May 14, 2016 10:18
Show Gist options
  • Save nikkatsa/9f3d3840ac0d29d2fb1f8a79cf6b45d8 to your computer and use it in GitHub Desktop.
Save nikkatsa/9f3d3840ac0d29d2fb1f8a79cf6b45d8 to your computer and use it in GitHub Desktop.
public void start() {
final ExecutorService left = Executors.newSingleThreadExecutor(new NamedThreadFactory("Left", true));
final Object leftObject = new Object();
final ExecutorService right = Executors.newSingleThreadExecutor(new NamedThreadFactory("Right", false));
final Object rightObject = new Object();
left.execute(() -> {
while (true) {
synchronized (leftObject) {
ThreadUtils.sleepWithoutInterruption(3000L, TimeUnit.MILLISECONDS);
log.info("Got left object, trying to acquire right now");
synchronized (rightObject) {
log.info("Got right object");
throw new RuntimeException("Shouldn't get both objects");
}
}
}
});
right.execute(() -> {
while (true) {
synchronized (rightObject) {
ThreadUtils.sleepWithoutInterruption(3000L, TimeUnit.MILLISECONDS);
log.info("Got right object, trying to acquire left now");
synchronized (leftObject) {
log.info("Got left object");
throw new RuntimeException("Shouldn't get both objects");
}
}
}
});
try {
Thread.currentThread().join();
} catch (final InterruptedException e) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment