This @Synchronized commentary warns that:
Locking on this or your own class object can have unfortunate
side-effects, as other code not under your control can lock on
these objects as well, which can cause race conditions and other nasty
threading-related bugs.
Avoiding race conditions is exactly the reason why I need to use the synchronized modifier, but when I see a warning like this, I realize that I may be causing more harm than good by not knowing everything about the system for which I am programming…
In my particular situation, I need to make sure that a specific method of a WebView-subclass is not interrupted by a PictureListener.onNewPicture().
That method was written by me, but it is only invoked by a Runnable.run() via a timer handler.
What should I check before deciding that it is safe to use the synchronized modifier to make sure that that timer-invoked method is not interrupted by PictureListener.onNewPicture()?
The solution is to use a private object to serve as the object’s lock, like this:
In the class definition:
or
In your code:
The reason why race conditions can occur is that other code has access to the objects locked on. Locking only private objects solves this.