Sunday 3 October 2021

ExpiringMap: Hello world application

Step 1: Get an instance of ExpiringMap.

Map<Integer, Employee> expiringMap = ExpiringMap.builder().maxSize(100).expiration(18, TimeUnit.SECONDS).build();

 

In the above example,

a.   ExpiringMap is can store Employee instances, where Integer is the key and Employee object is the value.

b.   I set the maximum size of the expiring map to 100 and

c.    expiry time of the entry to 18 seconds.

 

Step 2: Add entries to the expiringMap and test it accordingly.

expiringMap.put(1, new Employee(1, "Krishna"));

 

Find the below working application.

 

Employee.java

 

package com.sample.app.model;

public class Employee {

	private int id;
	private String name;

	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}

HelloWorld.java

package com.sample.app;

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

import net.jodah.expiringmap.ExpiringMap;
import com.sample.app.model.Employee;

public class HelloWorld {

	private static void sleepNSeconds(int n) throws InterruptedException {
		System.out.println("\nSleeping for " + n + " seconds");
		TimeUnit.SECONDS.sleep(5);
	}

	public static void main(String args[]) throws InterruptedException {
		Map<Integer, Employee> expiringMap = ExpiringMap.builder().maxSize(100).expiration(18, TimeUnit.SECONDS)
				.build();

		expiringMap.put(1, new Employee(1, "Krishna"));

		sleepNSeconds(5);
		System.out.println("Entry with key 1 -> " + expiringMap.get(1));

		sleepNSeconds(5);
		System.out.println("Entry with key 1 -> " + expiringMap.get(1));

		sleepNSeconds(5);
		System.out.println("Entry with key 1 -> " + expiringMap.get(1));

		sleepNSeconds(n);
		System.out.println("Entry with key 1 -> " + expiringMap.get(1));
	}
}


Output

Sleeping for 5 seconds
Entry with key 1 -> Employee [id=1, name=Krishna]

Sleeping for 5 seconds
Entry with key 1 -> Employee [id=1, name=Krishna]

Sleeping for 5 seconds
Entry with key 1 -> Employee [id=1, name=Krishna]

Sleeping for 5 seconds
Entry with key 1 -> null





 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment