How to avoid unfortunate side-effects when using synchronized
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 i开发者_JS百科s 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:
private Object syncRoot=new Object();
or
private static Object syncRoot=new Object();
In your code:
synchronized(syncRoot){
// put your code here
}
The reason why race conditions can occur is that other code has access to the objects locked on. Locking only private objects solves this.
Have a property in a class that you syncronhize on, rather than synchronizing on this
or WebView-subclass object
.
Most of those side effects would mostly affect server systems. I don't think that on Android you will have much of the problem as there is not much other code
that could touch your method.
精彩评论