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

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -