Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized Methods

If I have a synchronized public method and a private method:

public synchronized void doSomething() {
    doSomethingElse()
}

private void doSomethingElse() {
}

Do I need to synchronize the private method?

like image 872
andy Avatar asked Mar 30 '11 18:03

andy


2 Answers

Any methods called from a synchronized method (or from within a synchronized block) are run while still synchronized. You don't need to separately synchronize the private method if it is only called from synchronized methods.

like image 131
Ted Hopp Avatar answered Sep 23 '22 06:09

Ted Hopp


This is the intent of the @GuardedBy annotation. If you expect that a lock must be held when calling that method, annotate it with that and the name of the lock (in the example it would be:

@GuardedBy("this") private void doSomethingElse() {…}

Then you can check that the invariant is true with FindBugs.

You can also use the other net.jcip.annotations for describing the thread-safety or lack of it and have FindBugs validate these assumptions too. Of course, the book needs a plug as well.

like image 37
Jed Wesley-Smith Avatar answered Sep 25 '22 06:09

Jed Wesley-Smith