如何在将其发送到另一种方法时每隔30秒清空番石榴缓存?

我通过调用add方法从多个线程填充我的guava缓存。 现在从每30秒运行一次的后台线程,我想以primefaces方式将缓存中的任何内容发送到sendToDB方法?

以下是我的代码:

 public class Example { private final ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor(); private final Cache<Integer, List> cache = CacheBuilder.newBuilder().maximumSize(100000) .removalListener(RemovalListeners.asynchronous(new CustomRemovalListener(), executorService)) .build(); private static class Holder { private static final Example INSTANCE = new Example(); } public static Example getInstance() { return Holder.INSTANCE; } private Example() { executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { // is this the right way to send cache map? sendToDB(cache.asMap()); } }, 0, 30, SECONDS); } // this method will be called from multiple threads public void add(final int id, final Process process) { // add id and process into cache } // this will only be called from single background thread private void sendToDB(ConcurrentMap<Integer, List> holder) { // use holder here } } 

这是将cache映射发送到sendToDB方法的sendToDB方法吗? 基本上我想发送缓存中的所有条目30秒并清空缓存。 之后我的缓存将在接下来的30秒内再次填充,然后执行相同的过程?

我认为使用cache.asMap()可能不是正确的方法,因为它不会清空缓存,所以它会反映我的sendToDB方法中缓存上发生的所有更改?

怎么样:

 @Override public void run() { ImmutableMap> snapshot = ImmutableMap.copyOf(cache.asMap()); cache.invalidateAll(); sendToDB(snapshot); } 

这会将缓存的内容复制到新映射中,在特定时间点创建缓存的快照。 然后.invalidateAll()将清空缓存,之后快照将被发送到DB。

这种方法的一个缺点是它很活泼 – 在创建快照之后但在.invalidateAll()之前,可以将条目添加到缓存中,并且这些条目永远不会被发送到DB。 由于你的缓存也可能由于maximumSize()设置而逐出条目,我认为这不是一个问题,但是如果它是你想要在构建快照时删除条目,这将是这样的:

 @Override public void run() { Iterator> iter = cache.asMap().entrySet().iterator(); ImmutableMap> builder = ImmutableMap.builder(); while (iter.hasNext()) { builder.add(iter.next()); iter.remove(); } sendToDB(builder.build()); } 

使用这种方法,当调用sendToDB()时, cache实际上可能不是空的 ,但是在快照开始之前存在的每个条目都将被删除并将被发送到数据库。

或者,您可以创建一个包含Cache字段的包装类,并将该字段primefaces交换为新的空缓存,然后将旧缓存的内容复制到数据库并允许它进行GCed。