首页 > 解决方案 > 使用番石榴实现有序缓存

问题描述

我正在尝试在后台处理一些临时数据以避免主线程上的性能问题。

计划是通过维护插入顺序来收集数据并在后台处理它。应该首先处理最旧的消息。对缓存的读取和写入是同时发生的。性能是这里的关键。

有没有办法使用番石榴缓存来实现这一点?

这是我到目前为止的代码:

public static Cache<String, String> cache = CacheBuilder.newBuilder()
      .maximumSize(Integer.MAX_VALUE)
      .concurrencyLevel(5)
      .removalListener(notification -> {
        System.out.println("REMOVE : " + notification.getKey() + " CAUSE :" + notification.getCause().name());
      })
      .build();

// Different threads are adding data to this queue by calling
cache.put(key, value);

// The worker thread
public void run() {

    while (true) {
      if (cache.size() > 0) {
        final ConcurrentMap<String, String> cacheMap = cache.asMap();
        for (Map.Entry<String, String> entry : cacheMap.entrySet()) {
          //send data to a different system.
          cache.invalidate(entry.getKey());
        }
      } else {
        // Add delay of 5 sec
        Thread.sleep(5000);
      }
    }
}

标签: javaguava

解决方案


推荐阅读