使用同步时如何避免不幸的副作用
此 @Synchronized 评论警告说:
锁定此对象或您自己的类对象可能会带来不幸 副作用,因为其他代码不受您的控制可以锁定 这些对象也是如此,这可能会导致竞争条件和其他令人讨厌的情况 与线程相关的错误。
避免竞争条件正是我需要使用 synchronized 修饰符的原因,但是当我看到这样的警告,我意识到,由于不了解我正在编程的系统的一切,我可能会造成弊大于利......
在我的特殊情况下,我需要确保的具体方法WebView
子类不会被 PictureListener.onNewPicture()
中断。
该方法是我编写的,但它只能由 Runnable.run() 通过计时器处理程序调用。
在确定使用 synchronized
修饰符以确保计时器调用的方法不会被 PictureListener.onNewPicture()
中断之前,我应该检查什么?
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()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是使用私有对象作为对象的锁,如下所示:
在类定义中:
或
在您的代码中:
出现竞争条件的原因是其他代码可以访问锁定的对象。仅锁定私有对象可以解决这个问题。
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.
在您同步的类中拥有一个属性,而不是在
this
或 WebView 子类object
上同步。Have a property in a class that you syncronhize on, rather than synchronizing on
this
or WebView-subclassobject
.大多数副作用主要会影响服务器系统。我认为在 Android 上您不会遇到太多问题,因为没有太多
其他代码
可以触及您的方法。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.