I am reading SynchronizedMethodsOracleDoc and I am unable to understand this concept. It says that.
Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor: instances.add(this); But then other threads can use instances to access the object before construction of the object is complete.
What does this mean?
It also states that :-
Second, when a synchronized method exits,It automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.
What is the meaning of happens before relationship?
Can someone elaborate on these two points? Thanks.
Premature Leak
Leaking the reference to an object that is not yet completely created.
Example:
class Someclass{
public SomeClass(List list){
list.add(this); //this is leaked outside before complete creation, constructor is still not complete
//do some other chores to create this object
}
}
Some Thread 2:
listPassedToSomeclass //Thread is using this list and working on something
Now on calling add on the list from constructor you published the this
reference in the list which is shared by other thread, and now it can see the this reference added in the list before even the constructor has ended (Which means that the object is not in stable state and not properly created).
There is a possibility that the Thread 2 will get all sorts of weird behavior on using your object as the state will be unstable. So avoid leaking references.
Happens Before
