ScheduledExecutorService 性能

ScheduledExecutorService performance

我有一个最大大小为 5000 的对象列表。当一个对象在特定类型的时间内(如 5、10 或 100 秒)没有更新时,它将从列表中删除。

处理这种情况的最佳或首选方案是什么?

你推荐什么?

我实际上正在使用一个实现,它使用 Map<Object, Long> 来存储每个元素的过期时间,并使用 java.util.Timer 到 运行 每个 n 秒,删除每个过期元素。

我真的不能说它是最好的实现,因为我只将它用于几百个简单元素(即不复杂的对象)。

如果可以Google's Guava, you should give the Cacheclass试试

例如,您可以为每种类型的对象设置一个缓存:

LoadingCache<String, ObjectOfType1> type1Cache = CacheBuilder.newBuilder()
   .maximumSize(5000)
   .expireAfterWrite(5, TimeUnit.SECONDS)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<String, ObjectOfType1>() {
         public Graph load(String key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

对于Type2

LoadingCache<String, ObjectOfType2> type2Cache = CacheBuilder.newBuilder()
   .maximumSize(5000)
   .expireAfterWrite(10, TimeUnit.SECONDS)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<String, ObjectOfType2>() {
         public Graph load(String key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

然后,您可以像使用缓存一样使用缓存 Map:

ObjectOfType1 o1 = type1Cache.get("1");
ObjectOfType2 o2 = type2Cache.get("2");