简体   繁体   English

线程安全访问私有字段

[英]Thread safe access to private field

So I have the following scenario (can't share the actual code, but it would be something like this): 所以我有以下情况(无法共享实际的代码,但是会是这样):

public class Test
{
   private Object obj;

   public void init()
   {
       service.registerListener(new InnerTest());
   }

   public void readObj()
   {
       // read obj here
   }

   private class InnerTest implements Listener
   {
       public synchronized void updateObj()
       {
           Test.this.obj = new Object();
           // change the obj
       }
   }
}

The InnerTest class is registered as listener in a service. InnerTest类在服务中注册为侦听器。 That Service is running in one thread the calls to readObj() are made from a different thread, hence my question, to ensure consistency of the obj is it enough to make the UpdateObj() method synchronized? 该Service在一个线程中运行,对readObj()的调用是从另一个线程进行的,因此,我的问题是,确保obj一致性是否足以使UpdateObj()方法同步?

I would suggest using another object as a lock to ensure that the class only blocks when the obj is accessed: 我建议使用另一个对象作为锁,以确保该类仅在访问obj时才阻塞:

public class Test
{
   private final Object lock = new Object();
   private Object obj;

   public void init()
   {
       service.registerListener(new InnerTest());
   }

   public void readObj()
   {
       synchronized(lock){
           // read obj here
       }
   }

   private class InnerTest implements Listener
   {
       public void updateObj()
       {
           synchronized(Test.this.lock){
               Test.this.obj = new Object();
               // change the obj
           }
       }
   }
}

Then use that lock in all methods that need to have consistent access to obj . 然后在需要对obj进行一致访问的所有方法中使用该锁。 In your current example the readObj and updateObj methods. 在您当前的示例中, readObjupdateObj方法。

Also as stated in the comments, using synchronized on the method level in your InnerTest class, will not really work as you probably intended. 同样如注释中所述,在InnerTest类的方法级别上使用synchronized不会真正按照您的预期工作。 That is, because synchronized methods will use a synchronized block on the this variable. 也就是说,因为同步方法将在this变量上使用synchronized块。 Which just blocks your InnerTest class. 这只会阻塞您的InnerTest类。 But not the outer Test class. 但不是外部Test类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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