单例模式


1

  1. 1
  2. 2
  3. 列表3

    定义:一个类在系统中只产生一个实例
    优点:对于频繁使用的对象,可以省略new的时间,对于重量级对象来说是一比客观的系统性能提升

        内存使用频率低,减少GC次数,缩短GC停顿时间
//饿汉式    类第一次使用时必定会创建单例对象public class Singleton {    public static int STATUS=1;    private Singleton(){        System.out.println("Singleton is create");    }    private static Singleton instance = new Singleton();    public static Singleton getInstance() {        return instance;    } }//懒汉式    并发环境下,锁竞争激烈则性能较差public class LazySingleton {    private LazySingleton() {        System.out.println("LazySingleton is create");     }    private static LazySingleton instance = null;    public static synchronized LazySingleton getInstance() {        if (instance == null)            instance = new LazySingleton();        return instance;    }}//静态内部类式    //集合上述两种优势public class StaticSingleton {    public static int STATUS;    private StaticSingleton(){        System.out.println("StaticSingleton is create");    }    private static class SingletonHolder {        private static StaticSingleton instance = new StaticSingleton();    }    public static StaticSingleton getInstance() {        return SingletonHolder.instance;    }}
注意:另外还有一种双重检查模式来创建单例,这种模式丑陋且复杂,甚至在低版本中不能保证正确性,不推荐使用

不变模式

定义:一个对象一旦被创建,内部状态永远不发生改变,故永远为线程安全的使用场景:对象创建后,内部状态和数据不再发生变化         对象需要被共享,被多线程频繁访问    
public final class PCData {        //父类不变,子类也必须不变,但无法保证这一点,故使用final    private  final int intData;    //仅被赋值一次    public PCData(int d){        intData=d;    }    public PCData(String d){        intData=Integer.valueOf(d);    }    public int getData(){        return intData;    }    @Override    public String toString(){        return "data:"+intData;    }}
注意:String 类也是不变模式,保证了在多线程下的性能

生产者消费模式

生产者消费模式:无锁实现

Future模式

并行流水线

并行搜索

并行排序

并行算法:矩阵乘法

网络NIO

异步AIO