我有一个用于许多单例实现的通用接口.接口定义了可以抛出检查异常的初始化方法.
我需要一个工厂,它将按需返回缓存的单例实现,并想知道以下方法是否是线程安全的?
更新1:请不要建议任何第3部分图书馆,因为这可能需要获得法律许可,因为可能的许可问题:-)
更新2:此代码可能会在EJB环境中使用,因此最好不要生成其他线程或使用类似的东西.
interface Singleton
{
void init() throws SingletonException;
}
public class SingletonFactory
{
private static ConcurrentMap<String, AtomicReference<? extends Singleton>> CACHE =
new ConcurrentHashMap<String, AtomicReference<? extends Singleton>>();
public static <T extends Singleton> T getSingletonInstance(Class<T> clazz)
throws SingletonException
{
String key = clazz.getName();
if (CACHE.containsKey(key))
{
return readEventually(key);
}
AtomicReference<T> ref = new AtomicReference<T>(null);
if (CACHE.putIfAbsent(key, ref) == null)
{
try
{
T instance = clazz.newInstance();
instance.init();
ref.set(instance); // ----- (1) -----
return instance;
}
catch (Exception …Run Code Online (Sandbox Code Playgroud)