Sunday, 3 October 2021

ExpiringMap: Set expiration policy for individual entries

We can set the expiration policy to individual entry while inserting into the ExpiringMap.

 

Example

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

 

To allow for map entries to have individual expirations and for expirations to be changed, we need to set the flag 'variableExpiration' to true.

ExpiringMap<Integer, Employee> expiringMap = ExpiringMap.builder().variableExpiration().expiration(10, TimeUnit.SECONDS).expirationPolicy(ExpirationPolicy.CREATED).build();

 

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 + "]";
	}

}

 

ExpiryAtEntryLevelDemo.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

import com.sample.app.model.Employee;

import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;

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

	public static void main(String args[]) throws InterruptedException {
		ExpiringMap<Integer, Employee> expiringMap = ExpiringMap.builder().variableExpiration()
				.expiration(10, TimeUnit.SECONDS).expirationPolicy(ExpirationPolicy.CREATED).build();

		expiringMap.put(1, new Employee(1, "Krishna"), ExpirationPolicy.ACCESSED);
		expiringMap.put(2, new Employee(2, "Ram"));

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

		sleepNSeconds(8);
		System.out.println("\nEntry with key 1 -> " + expiringMap.get(1));
		System.out.println("Entry with key 2 -> " + expiringMap.get(2));

	}
}

 

Output

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

Sleeping for 8 seconds

Entry with key 1 -> Employee [id=1, name=Krishna]
Entry with key 2 -> null

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment