mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
fix code
This commit is contained in:
@@ -1,7 +1,12 @@
|
||||
package cn.hutool.cache.impl;
|
||||
|
||||
import cn.hutool.cache.CacheListener;
|
||||
import cn.hutool.core.lang.Opt;
|
||||
import cn.hutool.core.lang.mutable.Mutable;
|
||||
import cn.hutool.core.map.WeakConcurrentMap;
|
||||
|
||||
import java.lang.ref.Reference;
|
||||
|
||||
/**
|
||||
* 弱引用缓存<br>
|
||||
* 对于一个给定的键,其映射的存在并不阻止垃圾回收器对该键的丢弃,这就使该键成为可终止的,被终止,然后被回收。<br>
|
||||
@@ -24,4 +29,15 @@ public class WeakCache<K, V> extends TimedCache<K, V>{
|
||||
public WeakCache(long timeout) {
|
||||
super(timeout, new WeakConcurrentMap<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public WeakCache<K, V> setListener(CacheListener<K, V> listener) {
|
||||
super.setListener(listener);
|
||||
|
||||
final WeakConcurrentMap<Mutable<K>, CacheObj<K, V>> map = (WeakConcurrentMap<Mutable<K>, CacheObj<K, V>>) this.cacheMap;
|
||||
// WeakKey回收之后,key对应的值已经是null了,因此此处的key也为null
|
||||
map.setPurgeListener((key, value)-> listener.onRemove(Opt.ofNullable(key).map(Reference::get).map(Mutable::get).get(), value.getValue()));
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
@@ -26,11 +26,13 @@ public class WeakCacheTest {
|
||||
@Ignore
|
||||
public void removeByGcTest(){
|
||||
// https://gitee.com/dromara/hutool/issues/I51O7M
|
||||
// 经过GC,
|
||||
WeakCache<String, String> cache = new WeakCache<>(-1);
|
||||
cache.put("a", "1");
|
||||
cache.put("b", "2");
|
||||
|
||||
// 监听
|
||||
Assert.assertEquals(2, cache.size());
|
||||
cache.setListener(Console::log);
|
||||
|
||||
// GC测试
|
||||
int i=0;
|
||||
|
Reference in New Issue
Block a user