It could be used to ensure safe publication of non-final fields in the constructor.
public class Test {
int a;
public Test() {
synchronized (this) {
a = 5;
}
}
If another thread receives an object of type Test, and it also synchronizes on that instance of Test
, then this creates a happens-before relation between the end of the synchronized
block in the constructor, and the beginning of the synchronized
block in the other thread:
public class InOneThread {
public void run() {
InAnotherThread.test = new Test();
}
}
public class InAnotherThread {
public static Test test;
public void run() {
if (test == null) {
// Because assignment to `test` wasn't safely published, the
// field could be null even if it was assigned "earlier" in real
// time.
return;
}
synchronized(test) {
System.out.println(test.a);
// If no more modifications were made to 'a', this prints 5
// (guaranteed). Without the synchronized blocks, this could
// print 0 (zero) or 5.
}
}
}
However in practice this is almost never useful, since you need to synchronization mechanism to safely pass the instance of Test from one thread to another, and the synchronization mechanism itself almost certainly already introduces a happens-before relationship between the threads.
Still it could have its use in some highly specific concurrency component.
synchronized(this)
block within a constructor allowthis
object to escape or something...? – Mccarter