Java Synchronization callstack

Java Synchronization callstack

My question is, When i have above code and when I call doSomething() which is synchronized method is only this method will be synchronized or all the subsequent methods call like doIt1 & doIt2 also get synchronized ?

Only calls to doSomething() are synchronized; direct calls to doIt1() or others are not, unless those calls also use some locking of some kind.

That is, if you call doIt1(), the JVM wont look at the call sites from this method and see that oh, there is a synchronized call site to this method so I will synchronize accesses to this method as well.

In short: the JVM ultimately assumes that you know what you are doing.

If doSomething is called, it will be synchronized from start to finish, including when it invokes doIt1 and doIt2. If doIt1 or doIt2 are invoked directly (not through doSomething), they will not be synchronized, unless the synchronized keyword is also placed on them

Java Synchronization callstack

public static synchronized void doSomething(){
 //body
}

Is identical to

static void doSomething() {
 synchronized (this class) {
   //body
 } 
}

which is identical to

static void doSomething() {
 lock(this class) {
   //body
 } finally {
   unlock();
 }
}

Everything inside is synchronized because you do not release the key before body completes.

Leave a Reply

Your email address will not be published. Required fields are marked *