Sunday 3 October 2021

ExpiringMap: Set expiration time and policy at entry level

You can set variable expiration times and policies at entry level.

 

Example

expiringMap.put(2, new Employee(2, "Ram"), ExpirationPolicy.ACCESSED, 6, TimeUnit.SECONDS);

 

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

}

 

SetExpirationPolicyAtEntryLevel.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 SetExpirationPolicyAtEntryLevel {
	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().build();

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

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

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

	}
}

 

Output

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

Sleeping for 4 seconds

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

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment