使用同步时如何避免不幸的副作用

发布于 2024-12-05 12:48:07 字数 716 浏览 3 评论 0原文

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

埖埖迣鎅 2024-12-12 12:48:07

解决方案是使用私有对象作为对象的锁,如下所示:

在类定义中:

private Object syncRoot=new Object();

private static Object syncRoot=new Object();

在您的代码中:

synchronized(syncRoot){
  // put your code here
}

出现竞争条件的原因是其他代码可以访问锁定的对象。仅锁定私有对象可以解决这个问题。

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.

最偏执的依靠 2024-12-12 12:48:07

在您同步的类中拥有一个属性,而不是在 this 或 WebView 子类 object 上同步。

Have a property in a class that you syncronhize on, rather than synchronizing on this or WebView-subclass object.

甜点 2024-12-12 12:48:07

大多数副作用主要会影响服务器系统。我认为在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文