gpt4 book ai didi

java并发-带有监视器线程的单例设计

转载 作者:行者123 更新时间:2023-12-01 09:58:55 25 4
gpt4 key购买 nike

因此我有一个单例类

public final class HandlerCache {
//the cache maintains a handler per thread
private final Map<Thread, Handler> cache = new ConcurrentHashMap<>();

private final Thread monitor;

private static final HandlerCache INSTANCE = new HandlerCache();

private HandlerCache() {
monitor = new Thread() {
//periodically monitor cache and close handlers when a thread has died
}
monitor.start()
}

public static HandlerCache getInstance() {
return INSTANCE;
}

public Handler getHandler() throws Exception {
final Thread thread = Thread.currentThread();
Handler handler = cache.get(thread);

if (!(handler == null))
return handler;

handler = HandlerFactory.get(getHandlerFromName(thread.getName()));
cache.put(thread, handler);
return handler;
}

}

我在构造函数完成之前将单例实例泄漏到监视器线程,更好的方法是什么?

使缓存 volatile 可以解决问题吗?

最佳答案

正如 user2677485 所提到的,您应该使用 ThreadLocal 并实现initialValue 方法。另一点是Handler的实现应该实现finalize方法,这样当它被GC回收时,这个方法就会被调用,你可以清理你的资源。

代码可以简化为如下所示:

public class HandlerCache {

private static final handlers = new ThreadLocal<Handler>() {
protected Handler initializeValue() {
return HandlerFactory.get(...);
}
};

public static Handler getHandler() {
return handlers.get();
}

}

关于java并发-带有监视器线程的单例设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com