Java – Google common cache – the default value of maximumsize (and other “optional” settings) – you want a cache that uses all “available” memory

I just found guava through the search cache API (it's perfect for my needs)

In my opinion, a good default value for maximumsize is relative to runtime getRuntime(). freeMemory();

Finally, I want a cache that uses the memory available on a given system So I need an eviction policy to ask how much freememory () is available (possibly related to runtime. Getruntime()) maxMemory())

Solution

I asked me to question the same thing. I couldn't find anything on the Internet So I did this very primitive test

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;

public class CacheTest {
    public static void main(String[] args) {
        Cache<String,String> cache = CacheBuilder.newBuilder().build();
        int counter = 0;
        while(true){
            cache.put("key"+counter++,"value");
            System.out.println("size:"+cache.size());
        }
    }
}

As can be seen from the figure below, the memory usage increases to the maximum available space and becomes constant I waited for a few minutes and there was no outofmemoryerror What happens is that after a few seconds, a new entry is added to the map, so errors may occur in the future

Conclusion: you do not have to set the maximumsize value, but I recommend that you use some eviction policy (expireafteraccess or expireafterwrite) to clean up the cache and avoid outofmemoryerror And avoid reducing cache performance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>