synchronized
关键字package testsingleton;
//singleton---单例
/**
* 测试饿汉式单例模式
*/
public class SingletonDemo01 {
//类初始化时,立即加载这个对象(没有延迟加载的优势)。加载类时,天然的是线程安全的
private static SingletonDemo01 instance = new SingletonDemo01();
private SingletonDemo01() {//私有化构造器
}
//方法没有同步,调用效率高,
public static SingletonDemo01 getInstance() {
return instance;
}
}
getInstance()
方法都要同步,并发效率较低package testsingleton;
/**
* 测试懒汉式单例模式
* @author 橙汁儿Drk
*
*/
public class SingletonDemo2 {
//类初始化时,不初始化这个对象(延迟加载,真正用的时候再创建)。
private static SingletonDemo2 instance;
private SingletonDemo2() {//私有化构造器
}
//方法同步,调用效率低。
public static synchronized SingletonDemo2 getInstance() {
if (instance == null) {
instance = new SingletonDemo2();
}
return instance;
}
}
public class SingletonDemo03{
private static volatile SingletonDemo03 instance = null;
public static SingletonDemo03 getInstance(){
if(instance == null){
sychronized(SingletonDemo03.class){
if(sc == null){
sc = new SingletonDemo03();
}
}
}
return instance;
}
private SingletonDemo03(){}
}
package testsingleton;
/**
* 测试静态内部类实现单例模式
* 这种方式线程安全,调用效率高,实现延迟加载
* @author 橙汁儿Drk
*
*/
public class SingletonDemo3 {
private static class SingletonClassInstance{
private static final SingletonDemo3 instance = new SingletonDemo3();
}
//方法同步,调用效率低。
public static synchronized SingletonDemo3 getInstance() {
return SingletonClassInstance.instance;
}
public SingletonDemo3() {
}
}
package testsingleton;
/**
* 测试枚举实现单例模式
* 没有延迟加载
*
* @author 橙汁儿Drk
*
*/
public enum SingletonDemo4 {
//这个枚举元素,本身就是单例对象
INSTANCE;
//添加自己需要的操作
public void singletonOperation() {
}
}
System.out.println(SingletonDemo4.INSTANCE==SingletonDemo4.INSTANCE);
的结果为truepackage testsingleton;
import java.lang.reflect.Constructor;
/**
* 测试反射破解单例模式
* @author 橙汁儿Drk
*
*/
public class Client2 {
public static void main(String[] args) throws Exception {
SingletonDemo5 s1 = SingletonDemo5.getInstance();
SingletonDemo5 s2 = SingletonDemo5.getInstance();
System.out.println(s1);
System.out.println(s2);
//--------------------------------------------------------------
Class<SingletonDemo5> clazz = (Class<SingletonDemo5>) Class.forName("testsingleton.SingletonDemo5");
Constructor<SingletonDemo5> c = clazz.getDeclaredConstructor(null);
c.setAccessible(true);//设置私有可访问权限
SingletonDemo5 s3 = c.newInstance();
SingletonDemo5 s4 = c.newInstance();
System.out.println(s3);
System.out.println(s4);
}
}
//---------------------------------
//结果
testsingleton.SingletonDemo5@15db9742//s1
testsingleton.SingletonDemo5@15db9742//s2
//发现通过反射破解了懒汉式单例,创建了两个不同的对象
testsingleton.SingletonDemo5@6d06d69c//s3
testsingleton.SingletonDemo5@7852e922//s4
package testsingleton;
public class SingletonDemo5 {
private static SingletonDemo5 instance;
private SingletonDemo5() {
//通过抛出异常来阻止通过反射创建新的对象
if(instance != null) { throw new RuntimeException(); }
}
public static synchronized SingletonDemo5 getInstance() {
if (instance == null) {
instance = new SingletonDemo5();
}
return instance;
}
}
//反射调用构造方法时会抛出异常
package testsingleton;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 测试反射和反序列化破解单例模式
* @author 橙汁儿Drk
*
*/
public class Client2 {
public static void main(String[] args) throws Exception {
SingletonDemo5 s1 = SingletonDemo5.getInstance();
SingletonDemo5 s2 = SingletonDemo5.getInstance();
System.out.println(s1);
System.out.println(s2);
//通过反序列化的方式构造多个对象
FileOutputStream fos = new FileOutputStream("E:/MyJava/a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.close();
fos.close();
//反序列化,读取对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:/MyJava/a.txt"));
SingletonDemo5 s3 = (SingletonDemo5) ois.readObject();
System.out.println(s3);
}
}
//结果----------------------------------------
testsingleton.SingletonDemo5@15db9742//s1
testsingleton.SingletonDemo5@15db9742//s2
//反序列化读取对象后,发现是个新对象,破解了单例模式
testsingleton.SingletonDemo5@4c873330//s3
package testsingleton;
import java.io.Serializable;
/**
* 测试懒汉式单例模式(如何防止反射和反序列化漏洞)
* 没有延迟加载
*
* @author 橙汁儿Drk
*
*/
public class SingletonDemo5 implements Serializable{
private static SingletonDemo5 instance;
private SingletonDemo5() {
}
public static synchronized SingletonDemo5 getInstance() {
if (instance == null) {
instance = new SingletonDemo5();
}
return instance;
}
//反序列化时,如果定义了readResolve()方法则直接返回此方法指定的对象。而不需要再单独创建新对象
private Object readResolve() {
return instance;
}
}
五种单例模式在多线程下相对效率比较
| 饿汉式 | 22ms |
| — | — |
| 懒汉式 | 636ms |
| 静态内部类式 | 28ms |
| 枚举式 | 32ms |
| 双重检查锁式 | 65ms |
CountDownLatch类
countDown()
当前线程调用此方法,则计数减一(建议放在finally里执行)await()
调用此方法会抑制阻塞当前线程,知道计数器的值为0package testsingleton;
import java.util.concurrent.CountDownLatch;
/**
* 测试多线程环境下5种创建单例模式的效率
* @author 橙汁儿Drk
*
*/
public class Client3 {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
//同步辅助类
int threadNum = 10;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
//线程
for(int i = 0;i<10;i++) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i<100000;i++) {
Object o = SingletonDemo3.getInstance();
}
//每执行完一个线程,计数器减一
countDownLatch.countDown();
}
}).start();;
}
countDownLatch.await();//main线程阻塞,直到计数器变为0,才会继续往下执行
long end = System.currentTimeMillis();
System.out.println("总耗时:"+(end-start));
}
}