package com.iamitman.first;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.*;
/**
* 饿汉式:不论是否被使用,加载该类时都会被初始化
*/
public class B_Singleton {
public static final B_Singleton INSTANCE = new B_Singleton();
private B_Singleton() {
}
}
/**
* 枚举单例(与饿汉式一样)
*/
enum EnumSingleton {
INSTANCE
}
/**
* 静态代码块(饿汉式)
* 与第一种不同之处是如果想在创建时先从外部初始化一些数据,比如从配置文件获取数据,这种方式可以实现。
*/
class StaticSingleton {
public static final StaticSingleton INSTANCE;
private String info;
static {
try {
Properties properties = new Properties();
properties.load(StaticSingleton.class.getClassLoader().getResourceAsStream(""));
INSTANCE = new StaticSingleton(properties.getProperty(""));
} catch (IOException e) {
throw new RuntimeException();
}
}
private StaticSingleton(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
/**
* 懒汉式
* 线程不安全,需要加锁
*/
class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (instance == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingleton();
}
return instance;
}
/**
* 线程安全
*
* @return
*/
public static LazySingleton getInstanceSafe() {
synchronized (LazySingleton.class) {
if (instance == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingleton();
}
}
return instance;
}
/**
* 线程安全 + 性能好(已经初始化的情况下不再等待锁)
*
* @return
*/
public static LazySingleton getInstanceSafeAndFast() {
if (instance == null) {
synchronized (LazySingleton.class) {
if (instance == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new LazySingleton();
}
}
}
return instance;
}
public static void main(String[] args) {
Callable<LazySingleton> callable = new Callable<LazySingleton>() {
public LazySingleton call() throws Exception {
return LazySingleton.getInstance();
}
};
ExecutorService service = Executors.newFixedThreadPool(2);
Future<LazySingleton> future1 = service.submit(callable);
Future<LazySingleton> future2 = service.submit(callable);
LazySingleton lazySingleton1 = null;
try {
lazySingleton1 = future1.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
LazySingleton lazySingleton2 = null;
try {
lazySingleton2 = future2.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(lazySingleton1 == lazySingleton2);
service.shutdown();
}
}
/**
* 懒汉式 线程安全的(静态内部类)
* 只有在加载内部类的时候才会初始化实例
*/
class InnerSingleton {
private InnerSingleton() {
}
private static class Inner {
private static final InnerSingleton INSTANCE = new InnerSingleton();
}
public static InnerSingleton getInstance() {
return Inner.INSTANCE;
}
}