Reputation: 7856
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
?
Upvotes: 0
Views: 1556
Reputation: 7523
Note the following points about this code :
me
is private
No other public methods indirectly allow access to me
for outside code.
These two together allow the thread-safety for the me
reference. If the class is redesigned to have another public method as below :
public Safe someMethodForPublicAcess(){
return me;
}
Then the thread-safety is gone, even if the member me
is private
. This happens because an external code can now call this public method and pass me
to multiple threads which can do anything they like.
Upvotes: 0
Reputation: 200236
The only point is that while the constructor is running, you are not leaking this
by setting it to a private property. After the constructor completes and the caller receives the this
reference of the object, which is obviously the me
reference 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.
Upvotes: 3
Reputation: 14336
private
modifier by itself does not ensure thread safety. What does, though, is other threads not being able to access/see your object. Here, the instance of Safe
is being passed to MyThread, and isn't being stored/exposed elsewhere.
Upvotes: 0