目录
基于容器的单例模式
public class ContainerSingleton {
private static Map<String , Object> singletonMap = new HashMap<>();
public static void putInstance(String key , Object instance){
if(!"".equals(key) && key != null && instance != null){
if(!singletonMap.containsKey(key)){
singletonMap.put(key , instance);
}
}
}
public static Object getInstance(String key){
return singletonMap.get(key);
}
private ContainerSingleton(){
}
}
这种就是用一个map来管理,当然这种方式以刚开始多线程的方式来测试,也是线程不安全的,如果用HashTable线程就是安全的了,但是这样一来资源就会占用很大,所以不太推荐。所以具体用那种还是要根据实际情况来看。
基于ThreadLocal的线程“单例”
这里加引号的单例并不是真正的单例,而是对于线程的单例。
public class ThreadLocalInstance {
private static final ThreadLocal<ThreadLocalInstance> threadLocal = new ThreadLocal<ThreadLocalInstance>(){
@Override
protected ThreadLocalInstance initialValue() {
return new ThreadLocalInstance();
}
};
private ThreadLocalInstance(){
}
public static ThreadLocalInstance getInstance(){
return threadLocal.get();
}
}
public class T implements Runnable {
@Override
public void run() {
ThreadLocalInstance instance = ThreadLocalInstance.getInstance();
System.out.println(Thread.currentThread().getName() + " " + instance);
}
}
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new T());
Thread t2 = new Thread(new T());
t1.start();
t2.start();
System.out.println(ThreadLocalInstance.getInstance());
System.out.println(ThreadLocalInstance.getInstance());
System.out.println(ThreadLocalInstance.getInstance());
System.out.println(ThreadLocalInstance.getInstance());
System.out.println(ThreadLocalInstance.getInstance());
System.out.println(ThreadLocalInstance.getInstance());
}
}
结果:
可以看出,在同一线程内,获取到的对象是单例的。
单例模式在代码中的应用
Runtime,典型的饿汉式
Desktop
看一下里面的context#get
这里使用了两个同步锁,容器单例
ErrorContext