原文出自:http://www.javaworld.com/community/node/7692
There are two ways singletons are created using the Double Check Locking and the Holder Idiom for lazy loading. Both of them create a static singleton object which does not help garbage collection much.
In search of a new way to create singleton without using static object came across this solution which gets rid of creating object in static way and also helps garbage collection as we wrap singleton object with Soft Reference.
package com.singleton;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* SoftSingleton Idiom It does not create a static object and also creates a
* soft reference and thus in turn helps garbage collection.
*
* @author ajitkoti
*
*/
public class SingletonTest {
// This List would always contain only 1 Singleton object
private static List<SoftReference<SingletonTest>> singletonList = new ArrayList<SoftReference<SingletonTest>>();
// very imp to keep the permit as 1 if not other threads would acquire and
// create the Singleton
private static Semaphore semaphore = new Semaphore(1);
private SingletonTest() {
System.out.println("Hi I am a Singleton Just born");
}
/**
* Returns an instance of SingletonTest
*
* @return
*/
public static SingletonTest getInstance() {
if (singletonList.isEmpty() || singletonList.get(0).get() == null) {
try {
semaphore.acquire();
// Double check so that if the second thread acquires the permit
// ,
// while first Thread has all ready created the Singleton
if (singletonList.isEmpty()
|| singletonList.get(0).get() == null) {
// Only 1 Thread will ever enter here and create the
// Singleton
singletonList.add(new SoftReference<SingletonTest>(
new SingletonTest()));
}
semaphore.release();
} catch (InterruptedException e2) {
System.err.println("Could not create Singleton - "
+ e2.getMessage());
Thread.currentThread().interrupt(); // restore the interrupt
}
}
return singletonList.get(0).get();
}
/**
* Main method to test the Singleton creation
*
* @param args
*/
public static void main(String[] args) {
int noOfThreads = 1000;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
for (int i = 0; i < noOfThreads; i++) {
executor.execute(new Runnable() {
public void run() {
System.out.println("Calling and Creating singletonTest"
+ SingletonTest.getInstance());
}
});
}
executor.shutdown();
}
}
软引用单例模式
本文介绍了一种使用软引用实现的单例模式,该模式不使用静态对象,并且有助于垃圾回收。通过Semaphore确保线程安全地创建单例实例。
769

被折叠的 条评论
为什么被折叠?



