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

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

问题描述

每次在非最终类字段上同步时都会显示警告。以下是代码:

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 "guarding" it).

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

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