浅谈java单例模式延迟加载

                       浅谈java单例模式延迟加载

普通单例无法延迟加载,如:

public class Singleton
{
private Singleton()
{
System.out.println("Singleton is creating ....");
}

private static Singleton instance = new Singleton();

public static Singleton getInstance()
{
return instance;
}
}

于是我想到:

public class Singleton
{
private Singleton()
{
System.out.println("Singleton is creating ....");
}

private static Singleton instance = null;

public static synchronized Singleton getInstance()
{
if(null == instance)
{
instance = new Singleton();
}
return instance;
}
}


迭代开出几个线程去跑,测试性能,性能后者至少差上2个数量级,为实现延迟加载二引入的同步关键字反而降低了程序的性能,如何解决这个问题呢?



我们进行如下改进:

public class Singleton
{
private Singleton()
{
System.out.println("Singleton is creating ....");
}

private static class SingletonHolder
{
private static Singleton instance = new Singleton();
}

public static Singleton getInstance()
{
return SingletonHolder.instance;
}
}

类Singleton加载时,其内部类并不会被初始化,只有在getInstance方法被调用时才会加载,这种方式既可以做到延迟加载,又不用使用同步关键字,一举两得....


你可能感兴趣的:(java)