我在我的网络应用程序中实现了一个“管理器”,可以调用它来设置和获取当前线程所在的网站上下文(我们给我们的网站贴上白标签,所以网站上下文代表我们在哪个网站上)
我正在尝试找出执行此操作的最佳策略,目前我正在并发哈希映射中将线程存储到 WebSiteContexts:
private final ConcurrentHashMap<Thread, WebSiteContext> chm = new ConcurrentHashMap<Thread, WebSiteContext>();
在线程开始时(通过 Servlet 过滤器或通过手动设置),线程将关联到它的 WebSiteContext,
但想清理 Map 以避免内存泄漏。所以我想一种策略是遍历映射的 Thread 键以找出线程是否“活动”(thread.isAlive()),如果没有删除它,例如这样:
public class Cleaner implements Runnable {
private static final int INTERVAL = 6 * 1000; // 6 seconds
public Cleaner() {
}
public void run() {
// soo every interval iterate through the threads if they're dead then remove it from the map.
while(true) {
try {
Set<Thread> threads = chm.keySet();
Set<Thread> staleThreads = new HashSet<Thread>();
for (Thread tmpThread : threads) {
// if we get to a dead thread then clean the fucker up
if (!tmpThread.isAlive()) {
// think that we're going to get a run condition anyway
chm.remove(tmpThread);
}
}
Thread.sleep(INTERVAL);
} catch (Exception e) {
log.error("caught exception e:", e);
}
}
}
}
,但我想这需要我同步对地图的访问(或者是吗?)这是我想要避免的。
是否有任何“惯用”模式用于在 java 中的线程中存储属性或确实清理以 Thread 对象作为键的映射?我愿意使用 WeakReference / SoftReferences,或者如果有一些等价的 Thread.getCurrentThread().setAttribute(Object, Object),那就太好了
干杯西蒙B