Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Prevent Your Caches From Exploding

DZone's Guide to

Prevent Your Caches From Exploding

It's simple to do caching in Java by introducing a private HashMap that you query before calculating an object.

· Performance Zone
Free Resource

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

There are many scenarios in which you can benefit from caching commonly used objects in your application, especially in web- and microservice-oriented environments. The most simple type of caching you can do in Java is probably to introduce a private HashMap  that you query before calculating an object to make sure you don't do the job twice.

Here is an example of that:

public class PrimeService {

    private Map<Long, BigInteger> cache = new HashMap<>();

    public BigInteger getPrime(long minimum) {
        return cache.computeIfAbsent(minimum, 
            m -> BigInteger.valueOf(m).nextProbablePrime()
        );
    }

}

This is a quick solution to the problem, but sadly, it's not very efficient. After a few months of people entering all kinds of crazy numbers into the service, we will have a very large HashMapthat might cause you to run out of memory.

Here is a quick trick to solve that. Instead of using a HashMap, you can use a LinkedHashMap and simply override the method removeEldestEntry. That allows you to configure your own limit function to prevent the map from exploding.

public class PrimeService {

    public final static int CACHE_MAX_SIZE = 1_000;

    private Map<Long, BigInteger> cache = new LinkedHashMap<>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<ID, Boolean> eldest) {
            return size() > PrimeService.CACHE_MAX_SIZE;
        }
    };

    public BigInteger getPrime(long minimum) {
        return cache.computeIfAbsent(minimum, 
            m -> BigInteger.valueOf(m).nextProbablePrime()
        );
    }

}

We have now successfully limited the cache, preventing it from explosion. Old entries will be removed as new ones are added. It should be noted that this solution works well in small applications, but for more advanced scenarios you might want to use an external caching solution instead. 

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

Topics:
performace ,tutorial ,caching ,hashmap

Published at DZone with permission of Emil Forslund, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}