Reading through this excellent article about safe construction techniques by Brain Goetz, I got confused by a comment given inside the listing 5. Here is the code snippet:
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;
}
...
}
}
Why does he say this about me ? // Safe because "me" is not visible from any other thread. Can’t two threads simultanouesly access the instance variable me?
The only point is that while the constructor is running, you are not leaking
thisby setting it to a private property. After the constructor completes and the caller receives thethisreference of the object, which is obviously themereference as well, it can publish it to any thread, so indeed it will be accessible to any thread. But that was not the point Goetz was making.