java - Using volatile keyword for creating one instance -
i have following code:
public class entitymanagerfactoryproviderimpl implements entitymanagerfactoryprovider { private entitymanagerfactory entitymanagerfactory=null;//line xxx public entitymanagerfactory getfactory(){ if (entitymanagerfactory==null){ buildfactory(); } return entitymanagerfactory; } private synchronized void buildfactory(){ if (entitymanagerfactory!=null){ return; } entitymanagerfactory=... } }
so need entitymanagerfactory
instance created once - when getfactory()
first called.
must set variable entitymanagerfactory
on line xxx volatile case?
also, entitymanagerfactoryproviderimpl
osgi singleton declarative service, there 1 instance of class.
there theoretical possibilities multiple threads calling code in parallel; , due not using volatile, thread doesn't see updates thread b made.i have never encountered such behavior myself, surr: possible , when happens, strange bugs might come out of having 2 instances of same singleton.
you can study sei cert site full discussion of subject.
Comments
Post a Comment