0

Suppose there is a Synchronized method which in turn calls other ordinary methods as shown below:

public static synchronized void doSomething(){
 doIt1();
}

public doIt1(){
doIt2();
}

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

2
  • synchronized on what? Commented May 30, 2014 at 22:25
  • 2
    ...and you can't call an instance method from a static method. Commented May 30, 2014 at 22:33

4 Answers 4

1

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 won't 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think the OP's question is whether an invoked method is keeps the lock that its caller had (as opposed to unlocking before the invocation, and then presumably re-locking when the method returns).
@yshavit well, unless I am mistaken, I have answered the question and the answer is "no"
1

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

Comments

0
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.

Comments

0
When I call doSomething() which is a synchronized method,
is only this method thread safe or all the subsequent methods 
like doIt1 & doIt2 also thread safe?

Only doSomething() is thread safe because other threads can call doIt1() and doIt2().

public static synchronized void doSomething(){
  doIt1();
}

public static doIt1(){
 doIt2();
}

public static doIt2(){
  // more code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.