刚刚遇到一个问题,那就是单例模式Singleton的实现。想一下其实很简单,不过做起来还是有些复杂的!我一步一步来,一步一步去优化。
(1)首当其冲想的一实现方法:
public class Singleton{
private static Singleton the_instance = null;
public static Singleton getinstance(){
{
if(the_instance == null)
{
the_instance = new Singleton();
}
return the_instance;
}
}
这是一个简单的方法也是最危险的一个,忘记了多线程情况下出现多次实例化。
(2) 下面改进一下。
public class Singleton{
private static Singleton the_instance = null;
public static synchronized Singleton getinstance(){
{
if(the_instance == null)
{
the_instance = new Singleton();
}
return the_instance;
}
}
这样改进后就好多了,不过仔细一想还是问题不断。首先 the_instance 只会实例化一次,现实当中会大量的调用getinstance这个函数,当the_instance 实例化以后synchronized的意义就没有了,反而是累赘,音效程序效率。而且,我个人觉得,仅仅这样the_instance也是可能被是列化多次的,知道缓存的人就明白这个道理了。
(3)下面我再改进一下:
public class Singleton{
private static Singleton the_instance = null;
private static volatile boolean new_a_instance = false;
public static Singleton getinstance(){
{
if(the_instance == null)
{
New_Singleton();
}
return the_instance;
}
private static synchronized void New_Singleton()
{
if(new_a_instance == true)
{
return;
}
else
{
the_instance = new Singleton();
new_a_instance = true;
}
}
}
这样一下就感觉有点复杂了,用了锁synchronized 还不够!重点就是定义了一个静态变量new_a_instance,用这个变量来标示the_instance 是否已经初始化。
volatile:其目的是为了解决缓存带来的不幸!我们知道为了解决访问变量的速度慢我们用到了缓存,其目的就是将常用的(或是刚刚用的)数据存储在缓存中,下次用的时候就直接从缓存中读取。现实中各个线程都有自己的一个缓存区域,这样一来就出现了:缓存的数据和实际存储器上的数据不一。为了解决这个问题就出现了volatile。volatile修饰的数据没有多个拷贝,每次用的时候需要从内存中去读取。
当然,尽管这样,还是有问题的!没有很好的考虑“无序写入”这个特性!
(有什么不妥的地方欢迎大家指正,共同进步)