非最终字段的同步 [英] Synchronization of non-final field

查看:40
本文介绍了非最终字段的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我在非最终类字段上同步时都会显示警告.代码如下:

A warning is showing every time I synchronize on a non-final class field. Here is the code:

public class X  
{  
   private Object o;  

   public void setO(Object o)  
   {  
     this.o = o;  
   }  

   public void x()  
   {  
     synchronized (o) // synchronization on a non-final field  
     {  
     }  
   }  
 } 

所以我用以下方式改变了编码:

so I changed the coding in the following way:

 public class X  
 {  

   private final Object o;       
   public X()
   {  
     o = new Object();  
   }  

   public void x()  
   {  
     synchronized (o)
     {  
     }  
   }  
 }  

我不确定上面的代码是否是在非 final 类字段上同步的正确方法.如何同步非最终字段?

I am not sure the above code is the proper way to synchronize on a non-final class field. How can I synchronize a non final field?

推荐答案

首先,我鼓励你真正努力在更高的抽象级别上处理并发问题,即使用来自 java.util.concurrent 如ExecutorServices,Callables、Futures 等

First of all, I encourage you to really try hard to deal with concurrency issues on a higher level of abstraction, i.e. solving it using classes from java.util.concurrent such as ExecutorServices, Callables, Futures etc.

话虽如此,在非决赛场上同步本身并没有错误.您只需要记住,如果对象引用发生变化,同一部分代码可能会并行运行.即,如果一个线程运行同步块中的代码并且有人调用 setO(...),另一个线程可以在 相同的块上运行相同的同步块实例并发.

That being said, there's nothing wrong with synchronizing on a non-final field per se. You just need to keep in mind that if the object reference changes, the same section of code may be run in parallel. I.e., if one thread runs the code in the synchronized block and someone calls setO(...), another thread can run the same synchronized block on the same instance concurrently.

同步您需要独占访问的对象(或者,更好的是,一个专用于保护它的对象).

Synchronize on the object which you need exclusive access to (or, better yet, an object dedicated to guarding it).

这篇关于非最终字段的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆