java - What is happens before relations in Synchronization? What is premature object leak? -
i reading synchronizedmethodsoracledoc , unable understand concept. says that.
warning: when constructing object shared between threads, careful reference object not "leak" prematurely. example, suppose want maintain list called instances containing every instance of class. might tempted add following line constructor: instances.add(this); other threads can use instances access object before construction of object complete.
what mean?
it states :-
second, when synchronized method exits,it automatically establishes happens-before relationship subsequent invocation of synchronized method same object.
what meaning of happens before relationship?
can elaborate on these 2 points? thanks.
premature leak
leaking reference object not yet created.
example:
class someclass{ public someclass(list list){ list.add(this); //this leaked outside before complete creation, constructor still not complete //do other chores create object } }
some thread 2:
listpassedtosomeclass //thread using list , working on
now on calling add on list constructor published this
reference in list shared other thread, , can see reference added in list before constructor has ended (which means object not in stable state , not created).
there possibility thread 2 sorts of weird behavior on using object state unstable. avoid leaking references.
Comments
Post a Comment