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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With