如何使用可用内存作为参数通过 Guava Cache 缓存数据?
How to cache data via Guava Cache using available memory as parameter?
当可用的运行时内存接近溢出时,是否可以从缓存中删除数据?缓存实现如下:
Cache<String, Cache<String, List<String>>> cache = CacheBuilder.newBuilder()
.maximumWeight((int) ((Runtime.getRuntime().totalMemory() / 1024) * 0.9))
.weigher((Weigher<String, Cache<String, List<String>>>) (key, val) -> runtimeMemory())
.build();
public static int runtimeMemory() {
long totalMemory = Runtime.getRuntime().totalMemory() / 1024;
long freeMemory = Runtime.getRuntime().freeMemory() / 1024;
return (int) (totalMemory - freeMemory);
}
有没有工作?或者称重器为每个值汇总 runtimeMemory()?
如果您的 objective 是为了避免 运行 整个 JVM 内存不足,那么垃圾收集器是这项工作的合适人选。我建议你使用 soft-values,像这样:
Cache<String, Cache<String, List<String>>> cache = CacheBuilder.newBuilder()
.softValues()
.build();
这会设置一个缓存,将它存储在 SoftReference 中的任何值包装起来。软引用对象将以全局最近最少使用的方式进行垃圾收集,以响应内存需求和缓存中无效的条目。
Guava 的缓存——或任何堆上缓存实现,老实说——没有好的方法来做你要求的。软引用可能看起来有效,但更有可能导致糟糕的行为——例如您的 JVM 可能会执行连续不断的完整垃圾回收。
解决此问题的最佳方法是切实进行试验并找到适合您的 maximumSize
参数。您的实施也不会起作用,因为它不会尝试权衡一个特定的条目。
当可用的运行时内存接近溢出时,是否可以从缓存中删除数据?缓存实现如下:
Cache<String, Cache<String, List<String>>> cache = CacheBuilder.newBuilder()
.maximumWeight((int) ((Runtime.getRuntime().totalMemory() / 1024) * 0.9))
.weigher((Weigher<String, Cache<String, List<String>>>) (key, val) -> runtimeMemory())
.build();
public static int runtimeMemory() {
long totalMemory = Runtime.getRuntime().totalMemory() / 1024;
long freeMemory = Runtime.getRuntime().freeMemory() / 1024;
return (int) (totalMemory - freeMemory);
}
有没有工作?或者称重器为每个值汇总 runtimeMemory()?
如果您的 objective 是为了避免 运行 整个 JVM 内存不足,那么垃圾收集器是这项工作的合适人选。我建议你使用 soft-values,像这样:
Cache<String, Cache<String, List<String>>> cache = CacheBuilder.newBuilder()
.softValues()
.build();
这会设置一个缓存,将它存储在 SoftReference 中的任何值包装起来。软引用对象将以全局最近最少使用的方式进行垃圾收集,以响应内存需求和缓存中无效的条目。
Guava 的缓存——或任何堆上缓存实现,老实说——没有好的方法来做你要求的。软引用可能看起来有效,但更有可能导致糟糕的行为——例如您的 JVM 可能会执行连续不断的完整垃圾回收。
解决此问题的最佳方法是切实进行试验并找到适合您的 maximumSize
参数。您的实施也不会起作用,因为它不会尝试权衡一个特定的条目。