gpt4 book ai didi

java - 为什么我的 WeakHashMap 条目没有被 GC 删除?

转载 作者:行者123 更新时间:2023-11-29 08:20:29 25 4
gpt4 key购买 nike

我有一个类来管理几个功能的锁对象。我发现 WeakHashMap 应该符合我的要求。这是我的代码:

public static class FeatureLockManager {
private final Map<Object, WeakKeyLockPair> locks;
private String domain;

public FeatureLockManager(String domain) {
this.domain = domain;
locks = new WeakHashMap<Object, WeakKeyLockPair>();
}

public Lock getLock(Object feature) {
if (locks.get(feature) == null) {
synchronized (locks) {
locks.computeIfAbsent(feature, l -> new WeakKeyLockPair(feature, new ReentrantLock()));
}
}
return locks.get(feature);
}

private static class WeakKeyLockPair implements Lock {
private final Reference<Object> feature;
private final Lock lock;

private WeakKeyLockPair(Object feature, Lock lock) {
this.feature = new WeakReference<Object>(feature);
this.lock = lock;
}
... }
}

但是经过简单的测试,我发现锁对象在GC之后并不会被移除。

public static void main(String[] args) throws InterruptedException {
FeatureLockManager test = new FeatureLockManager("test");
Lock lock = test.getLock("add user");
System.out.println(lock.hashCode());
// do thing
System.gc();
Thread.sleep(1000);
Lock lock1 = test.getLock("add user");
System.out.println(lock1.hashCode());
System.out.println(lock1 == lock);
}

你能告诉我我的实现有什么问题吗?提前致谢!

最佳答案

根据WeakHashMap的java文档

Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector.

您的 FeatureLockManager 类仍然具有对 WeakHashMap 的关键元素(“添加用户”)的强引用。

有关更多详细信息,请查看 documentation

关于java - 为什么我的 WeakHashMap 条目没有被 GC 删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303194/

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