ExpiringMap is a high performance, thread-safe ConcurrentMap implementation that expires entries

Java without Java Collection is really hard to imagine. I spend almost couple of hours a day working on Java Projects for my clients.

HashMap, Map, Static Objects, Java Interface are the most commonly used terms.

Sometime back I’ve written an article on How to remove elements from HashMap Automatically using Java Timer and Futures Object?

In this tutorial, we will go over similar concept but not using Timer but ExpiringMap 🙂

java – Map with automatically expiring elements

Let’s get started:

Step-1.

Create Java Class CrunchifyNetJodahExpiringMapExample.java.

Step-2.

Add Maven net.jodah.expiringmap Dependency.

If you don’t see pom.xml file into your Eclipse Environment then follow this steps.

<dependency>
    <groupId>net.jodah</groupId>
    <artifactId>expiringmap</artifactId>
    <version>0.5.7</version>
</dependency>

Step-3

Create object curnchifyMap with Expiration time set to 5 seconds.

Step-4

  • Add an element to crunchifyMap every second
  • We will also print the number of element for that map using size() method

Step-5

As you will see in Output, there will not be more than 5 elements over 5 seconds into crunchifyMap.

Complete Java Example:

package crunchify.com.tutorial;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import net.jodah.expiringmap.ExpiringMap;

/**
 * @author Crunchify.com
 * 
 *         - ExpiringMap is a high performance, thread-safe ConcurrentMap implementation that expires entries. 
 *         - Ideally no performance overhead without any external dependency
 * 
 */

public class CrunchifyNetJodahExpiringMapExample {

        // Create Exipring Map called crunchifyMap with expiry time 5 seconds
        private static Map<String, Double> crunchifyMap = ExpiringMap.builder().expiration(5, TimeUnit.SECONDS).build();

        public static void main(String[] args) {
                {
                        // Let's keep running loop for testing
                        while (true) {
                                try {

                                        // Just wait for a second everytime
                                        Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }

                                // Add Element to Map crunchifyMap
                                addElement();

                                // Print Element to Map crunchifyMap
                                printElement();
                        }

                }
        }

        private static void printElement() {

                log("crunchifyMap Size: " + crunchifyMap.size() + "\n");
        }

        // NOTE: We are adding Unique Element to Map Every time.
        private static void addElement() {

                double randomValue = Math.random();

                // If the specified key is not already associated with a value (or is mapped to null) associates it with the
                // given value and returns null, else returns the current value.
                crunchifyMap.putIfAbsent("Crunchify " + randomValue, randomValue);
                
                log("+++++ Element added to crunchifyMap:" + randomValue);

        }

        private static void log(String string) {
                System.out.println(string);

        }
}

Console Output:

Just run above program as a Java Application and you will see result similar to this.

After 5 second expiry – keys are automatically getting expired.

/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/java -/Users/app/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.31/log4j-over-slf4j-1.7.31.jar crunchify.com.tutorial.CrunchifyNetJodahExpiringMapExample
====> Element added to crunchifyMap => 0.48760401691160116
crunchifyMap Size: 1

====> Element added to crunchifyMap => 0.6299734553921958
crunchifyMap Size: 2

====> Element added to crunchifyMap => 0.18338241691080748
crunchifyMap Size: 3

====> Element added to crunchifyMap => 0.8742412816761246
crunchifyMap Size: 4

====> Element added to crunchifyMap => 0.13217201962074232
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.07235156805033105
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.6477405601398932
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.564886411084217
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.8749054727687872
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.3654795469820278
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.5227149932981
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.9303076239823368
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.9475064492136289
crunchifyMap Size: 5

====> Element added to crunchifyMap => 0.3190524067258429
crunchifyMap Size: 5


Process finished with exit code 130 (interrupted by signal 2: SIGINT)

Let us know if you face any issue running above program.

The post How to use net.jodah.ExpiringMap Maven Java Utility to Remove Expired Objects from HashMap Automatically? appeared first on Crunchify.