java - 使用番石榴实现有序缓存
问题描述
我正在尝试在后台处理一些临时数据以避免主线程上的性能问题。
计划是通过维护插入顺序来收集数据并在后台处理它。应该首先处理最旧的消息。对缓存的读取和写入是同时发生的。性能是这里的关键。
有没有办法使用番石榴缓存来实现这一点?
这是我到目前为止的代码:
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);
}
}
}
解决方案
推荐阅读
- jenkins - Jenkins Pipeline:如何从管道内禁用当前作业?
- swift - 为什么每次上传照片时,firebase 存储都会覆盖应保留所有用户图像的存储?
- javascript - 使用 JS 从 CSS 更改 BackgroundImage
- get - 如何在 apex 中创建 httpsrequest 'Get',然后在 Salesforce 中更新记录
- html - 移动浏览器无法显示特定图像
- reactjs - 未定义无法从 app.js 解析模块 react-navigation-stack
- python - 在pygame中执行for循环后图像不会保留在屏幕上
- android - 获取.NET CORE 3 webApi时反应本机引发网络错误
- python - 装饰器可以装饰递归函数吗?
- function - 动态调用函数