【问题标题】:Does a "private" modifier also ensure Thread safety in Java“私有”修饰符是否也确保 Java 中的线程安全
【发布时间】:2012-07-02 08:19:21
【问题描述】:

阅读了 Brain Goetz 关于安全构造技术的优秀文章this,我对清单 5 中给出的评论感到困惑。这是代码 sn-p:

public class Safe { 

 private Object me;
 private Set set = new HashSet();
 private Thread thread;

 public Safe() { 
 // Safe because "me" is not visible from any other thread
 me = this;

// Safe because "set" is not visible from any other thread
 set.add(this);

// Safe because MyThread won't start until construction is complete
// and the constructor doesn't publish the reference
   thread = new MyThread(this);
}

public void start() {
   thread.start();
 }

private class MyThread(Object o) {

private Object theObject;

public MyThread(Object o) { 
  this.theObject = o;
}

...
 }
}

他为什么这么说me// Safe because "me" is not visible from any other thread。两个线程不能同时访问实例变量me吗?

【问题讨论】:

  • 我是私有的,为什么线程可以访问它?

标签: java concurrency synchronization this java.util.concurrent


【解决方案1】:

唯一的一点是,在构造函数运行时,您不会this 设置为私有属性。在构造函数完成并且调用者接收到对象的this引用后,显然也是me引用,它可以将它发布到任何线程,因此它确实可以被任何线程访问。但这不是 Goetz 的重点。

【讨论】:

    【解决方案2】:

    private 修饰符本身并不能确保线程安全。但是,其他线程无法访问/查看您的对象是什么。在这里,Safe 的实例被传递给 MyThread,并且没有被存储/暴露在其他地方。

    【讨论】:

      【解决方案3】:

      请注意有关此代码的以下几点:

      1. meprivate
      2. 没有其他公共方法间接允许外部代码访问me

        这两个一起允许me 引用的线程安全。如果该类被重新设计为具有另一个公共方法,如下所示:

      public Safe someMethodForPublicAcess(){ return me; }

      即使成员meprivate,线程安全也消失了。发生这种情况是因为外部代码现在可以调用此公共方法并将me 传递给多个线程,这些线程可以做任何他们想做的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 2020-01-15
        • 2015-09-26
        • 1970-01-01
        • 2021-08-25
        • 1970-01-01
        相关资源
        最近更新 更多