gpt4 book ai didi

java - 加载缓存 : RemovalListener Returns null Value

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

我最近开始使用 LoadingCache 类,但遇到了一些意外行为。我现在知道解决方案了,但我发布了这个问题,以便其他人可以从中学习。

基本上,我在缓存中为某个键放置了一个非空值。关键是值在文件中的位置,使用 CacheLoader.load() 方法,可以从文件中读取值。目前 LoadingCache 由单个线程使用。

当我运行我的应用程序时,删除通知监听器被调用,并且之前用于插入非空值的键的空值。我知道这一点是因为我使用断言语句来检查进入缓存的所有值是否不为空(无论如何都不应该发生)。我也可以看到这一点,因为我在 CacheLoader.load( ) 调用的方法中打印了 key : CacheLoader.load( ) 是唯一 可以调用打印 key 的方法的方法。此外,此方法不能返回空值。

如果有人能告诉我我做错了什么,我将不胜感激。

下面是我对加载缓存的定义

    private LoadingCache<Long,T> gcache( ) {
@SuppressWarnings( Constants.UNCHECKED )
final CacheLoader<Long,T> loader =
new CacheLoader<Long,T>() {
public T load(Long key) {
// This following method _did_ print the key for which
// the RemovalNotification listener returns a null value.
// See output further on.
return getElement( key );
}
};
@SuppressWarnings( Constants.UNCHECKED )
final RemovalListener<Long,T> listener
= new RemovalListener<Long,T>( ) {
@Override
public void onRemoval( RemovalNotification<Long,T> notification ) {
final T value = notification.getValue( );
////////////////////////////////////////////////////////////////////////////
if (value == null) {
System.out.println( "????: " + notification.getKey( ) );
}
assert( value != null);
////////////////////////////////////////////////////////////////////////////
if (!value.immutable( )) {
put( notification.getKey( ), value );
}
}
};
@SuppressWarnings( Constants.UNCHECKED )
final LoadingCache<Long, T> gcache
= CacheBuilder.newBuilder( )
.softValues( )
.removalListener( listener )
.build( loader );
return gcache;
}

private T getElement( long pos ) {
// Critical section, but at the moment there's only one thread.
enter( );
seek( pos );
final T creation = inflator.inflate( this );
///////////////////////////////////////////////////////////////////////
System.out.println( "getElement: pos = " + pos );
assert( creation != null );
///////////////////////////////////////////////////////////////////////
leave( );
return creation;
}

一些输出:

[ cut ]
getElement: pos = 362848
[ cut ]
????: 362848

在问号之后,我得到了无法控制的输出量,并且 JVM 很难停止。在终止应用程序之前,我必须多次按下该键。 (当然 kill 也可以,但键盘速度稍快。)

最佳答案

我只是猜测:在 RemovalNotification 的 javadoc 中是这样写的

A notification of the removal of a single entry. The key and/or value may be null if they were already garbage collected.

并且您正在使用 softValues()。当值被 GC 处理时,整个条目将从缓存中删除,并且键也可能被收集。

关于java - 加载缓存 : RemovalListener Returns null Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12132193/

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