gpt4 book ai didi

带有 removeEldestEntry 的 Java LinkedHashMap 导致 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-11-30 06:19:41 26 4
gpt4 key购买 nike

错误看起来像这样

Exception in thread "Thread-1" java.lang.NullPointerException
at java.util.LinkedHashMap$Entry.remove(LinkedHashMap.java:332)
at java.util.LinkedHashMap$Entry.recordAccess(LinkedHashMap.java:356)
at java.util.LinkedHashMap.get(LinkedHashMap.java:304)
at Server.getLastFinishedCommands(Server.java:9086)
at Server.processPacket(Server.java:484)
at PacketWorker.run(PacketWorker.java:34)
at java.lang.Thread.run(Thread.java:744)

getLastFinishedCommands 中我使用

   public List<CCommand> getLastFinishedCommands(UserProfile player) {
List<CCommand> returnList = new ArrayList<CCommand>();

if(!finishedCommands.containsKey(player.myWebsitecmd-1)) {
getSavedState(player);
return null;
}

try { //<-- added this try/catch so it doesn't happen again.
//Get commands.
CCommand cmd;
long i;
long startIndex = player.myWebsitecmd;
long endIndex = startIndex+LIMIT_COMMANDS;

for(i = startIndex; i <= endIndex; i++) {
cmd = finishedCommands.get(i); //<-- this is line 9086
if(cmd == null) {
return returnList;
}
returnList.add(cmd);
}
} catch(Exception e) {} //<-- added this try/catch so it doesn't happen again.
return returnList;
}

我想制作一个自动删除旧条目的 map ,所以我使用了这个片段

public static <K, V> Map<K, V> createLRUMap(final int maxEntries) {
return new LinkedHashMap<K, V>(maxEntries*3/2, 0.7f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries;
}
};
}

是这样用的

public static int final MAX_COMMANDS_QUEUE = 5000;
public Map<Long, CCommand> finishedCommands = createLRUMap(MAX_COMMANDS_QUEUE);

显然,这是某种 CocurrentModifcationException,在与多个线程一起使用时会发生。但是为什么它会在内部崩溃,有人知道我如何将其与 CocurrentHashMap 一起使用吗?我试图解决这个问题,而不是仅仅在整个 getLastFinishedCommands 函数周围放置一个 try/catch。

我想要一个能够清除旧垃圾但仍保留至少 5000 个键/值条目的 Map。

最佳答案

根据堆栈跟踪,我假设代码试图从索引中删除其项目已被另一个线程删除的值。这使得它在访问 null 引用的属性时抛出 NPE。也许,你应该尝试同步集合

来自LinkedHashMap的文档

Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   Map m = Collections.synchronizedMap(new LinkedHashMap(...));

关于带有 removeEldestEntry 的 Java LinkedHashMap 导致 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778981/

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