Singleton: Difference between revisions

Content added Content deleted
Line 300: Line 300:


===Thread-safe===
===Thread-safe===
Double-checked locking

only use with Java 1.5+
<java>
<java>
class Singleton
class Singleton
{
{
private static Singleton myInstance;
private static Singleton myInstance;
public static synchronized Singleton getInstance()
public static Singleton getInstance()
{
{
if (myInstance == null)
if (myInstance == null)
myInstance = new Singleton();
synchronized(this)
if (myInstance == null)
myInstance = new Singleton();


return myInstance;
return myInstance;