Skip to content

Instantly share code, notes, and snippets.

@guavabot
Created January 15, 2016 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guavabot/45ca5be8d9568d783d9f to your computer and use it in GitHub Desktop.
Save guavabot/45ca5be8d9568d783d9f to your computer and use it in GitHub Desktop.
/**
* Proves that we can put a condition in the parameter of a synchronized block.
*
* <p>Ex.
* <br>{@code synchronized (first ? mLock1 : mLock2)}
*/
public class ConditionSynchronizedBlock {
public static void main(String [ ] a) {
ConditionSynchronizedBlock tested = new ConditionSynchronizedBlock();
new Thread(new Runnable() {
public void run() {
tested.lock1();
}
}).start();
new Thread(new Runnable() {
public void run() {
tested.acquire(false);
tested.acquire(true);
}
}).start();
}
private final Object mLock1 = new Object();
private final Object mLock2 = new Object();
private void lock1() {
printThreadMsg("locking first");
synchronized (mLock1) {
printThreadMsg("locked first");
try {
printThreadMsg("pausing");
Thread.sleep(2_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
printThreadMsg("released first");
}
private void acquire(boolean first) {
printThreadMsg("acquiring " + (first ? "first" : "second"));
synchronized (first ? mLock1 : mLock2) {
printThreadMsg("acquired " + (first ? "first" : "second"));
}
printThreadMsg("released " + (first ? "first" : "second"));
}
private void printThreadMsg(String msg) {
String fullMsg = String.format("%d %s: %s", System.nanoTime(), Thread.currentThread().getName(), msg);
System.out.println(fullMsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment