简体   繁体   中英

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 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:

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.

在您要同步的类中具有一个属性,而不要在this或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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM