Robert
Robert

Reputation: 8683

Java synchronized method calling not synchronized method

I have code like this:

public class Example {
    public synchronized void doSomething() {
        // ...
        doSomethingElse();
        // ...
    }

    private void doSomethingElse() {
        // ...
    }
}

Since doSomething is the only place where doSomethingElse is called and doSomething is synchronized, is it still necessary to make doSomethingElse synchronized?

The Java Language Specification says in the beginning of chapter 8 on Classes: "A synchronized method [...] automatically locks an object before executing its body and automatically unlocks the object on return". I'd assume that calling another method is not returning, so the above code should be correct.

JLS example 8.4.3.6-1 on synchronized monitors seems to confirm my understanding.

On the other hand, I guess making doSomethingElse synchronized won't hurt; except maybe for a small performance hit as per What is the synchronization cost of calling a synchronized method from a synchronized method? (which I don't care that much about; correctness is more important).

Am I missing something?

Upvotes: 2

Views: 1228

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726909

is it still necessary to make doSomethingElse synchronized?

No. Since the method is private, and the only context in which it could be called is synchronized as well, doSomethingElse does not need to be synchronized.

Note that it does not hurt to make doSomethingElse synchronized, for two reasons:

  • In case someone else changes your code to call doSomethingElse from some other place that is not synchronized, you would be safe. Re-entering a lock that the thread already owns is very cheap, so you do not need to worry about performance consequences.
  • When other people read your code, and see you accessing shared resources from doSomethingElse without synchronization, they are not surprised at how you can get away with that.

Also note that it is important that both methods are non-static. Had doSomethingElse been static and needed access to mutable static resources, you would need to synchronize it separately from doSomething.

Upvotes: 4

Related Questions