单例模式和软引用[Soft Singleton Idiom]

原文出自: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();

	}

}
 


 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值