First rule of thumb, try to avoid singletons as much as possible. Singleton is an anti pattern in many cases. I am alarmed at the amount of singletons I am starting to see in code reviews! Abuse of the singleton pattern is a sign of bad design. It also indicates that the programmer is being lazy and not thinking through how state is going to be managed.
2nd rule; if you can't avoid singletons, the best way to do it would be to create the instance while initializing the class level "instance" attribute. On Fri, Dec 19, 2014 at 3:19 PM, Manuranga Perera <[email protected]> wrote: > > ---------- Forwarded message ---------- > From: Manuranga Perera <[email protected]> > Date: Fri, Dec 19, 2014 at 3:15 PM > Subject: What is the recommended way to initialize singleton > To: dev <[email protected]> > Cc: Afkham Azeez <[email protected]>, Sameera Jayasoma <[email protected]>, > Sameera Perera <[email protected]>, Ruchira Wageesha <[email protected]> > > Following kind of double locking code doesn't work [1] for singletons. > (please remove this if you see it in any place in the platform) > > if(instance == null) { > synchronized(MyClass.class) { > if(instance == null) { > instance = new MyClass(); > } > } > } > return instance; > > > There are multiple ways we can do this right. What is the best practice > for defining singletons in unavoidable situations? > > [1] http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html > > -- > With regards, > *Manu*ranga Perera. > > phone : 071 7 70 20 50 > mail : [email protected] > > > -- > With regards, > *Manu*ranga Perera. > > phone : 071 7 70 20 50 > mail : [email protected] > > -- > You received this message because you are subscribed to the Google Groups > "WSO2 Engineering Group" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > For more options, visit https://groups.google.com/a/wso2.com/d/optout. > -- *Afkham Azeez* Director of Architecture; WSO2, Inc.; http://wso2.com Member; Apache Software Foundation; http://www.apache.org/ * <http://www.apache.org/>* *email: **[email protected]* <[email protected]> * cell: +94 77 3320919blog: **http://blog.afkham.org* <http://blog.afkham.org> *twitter: **http://twitter.com/afkham_azeez* <http://twitter.com/afkham_azeez> *linked-in: **http://lk.linkedin.com/in/afkhamazeez <http://lk.linkedin.com/in/afkhamazeez>* *Lean . Enterprise . Middleware*
_______________________________________________ Dev mailing list [email protected] http://wso2.org/cgi-bin/mailman/listinfo/dev
