public abstract class DelegatorFactory implements Factory<Delegator, String> {
public static final String module = DelegatorFactoryImpl.class.getName();
private static final ConcurrentHashMap<String, Future<Delegator>> delegators = new ConcurrentHashMap<String, Future<Delegator>>();
private static final ThreadGroup DELEGATOR_THREAD_GROUP = new ThreadGroup("DelegatorFactory");
private static final ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(DELEGATOR_THREAD_GROUP, "delegator-startup", Runtime.getRuntime().availableProcessors(), 10, true);
/**
*@author 郑小康
*
* 根据delegatorName调用getDelegatorFuture方法,获取当前delegator的 Future<Delegator>
*
* 而后调用get方法获取Delegator实例
*
* */
public static Delegator getDelegator(String delegatorName) {
Future<Delegator> future = getDelegatorFuture(delegatorName);
try {
return future.get();
} catch (ExecutionException e) {
Debug.logError(e, module);
return null;
} catch (InterruptedException e) {
Debug.logError(e, module);
return null;
}
}
/**
* @author 郑小康
*
* 根据delegatorName获取Future<Delegator> 如果为空,新创建一个FutureTask<Delegator>将其加入到缓存中去
*
* 将这个futureTask给提交到线程池,futureTask中存放的是DelegatorConfigurable实例对象
*
*
* */
public static Future<Delegator> getDelegatorFuture(String delegatorName) {
if (delegatorName == null) {
delegatorName = "default";
//Debug.logWarning(new Exception("Location where getting delegator with null name"), "Got a getGenericDelegator call with a null delegatorName, assuming default for the name.", module);
}
do {
Future<Delegator> future = delegators.get(delegatorName);
if (future != null) {
//Debug.logInfo("got delegator(future(" + delegatorName + ")) from cache", module);
return future;
}
FutureTask<Delegator> futureTask = new FutureTask<Delegator>(new DelegatorConfigurable(delegatorName));
//Debug.logInfo("putting delegator(future(" + delegatorName + ")) into cache", module);
if (delegators.putIfAbsent(delegatorName, futureTask) != null) {
continue;
}
executor.submit(futureTask);
} while (true);
}
public static final class DelegatorConfigurable implements Callable<Delegator> {
private final String delegatorName;
public DelegatorConfigurable(String delegatorName) {
this.delegatorName = delegatorName;
}
/**
* 获取delegator的具体方法
* 并做了分布式缓存和ECA Handler FIXME:未研究
* */
public Delegator call() throws ClassNotFoundException {
try {
Delegator delegator = UtilObject.getObjectFromFactory(DelegatorFactory.class, delegatorName);
// setup the Entity ECA Handler
delegator.initEntityEcaHandler();
// setup the distributed CacheClear
delegator.initDistributedCacheClear();
return delegator;
} catch (ClassNotFoundException e) {
Debug.logError(e, module);
throw e;
}
}
}
}