Monday, 4 October 2021

ExpiringMap: Add expiration listener at run time

Expiration listeners can also be added and removed on the fly using 'addExpirationListener' and 'removeExpirationListener' methods.

 

Example

expiringMap.addExpirationListener((key, employee) -> ((Employee) employee).logOnExpire());

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 + "]";
	}
	
	public void logOnExpire() {
		System.out.println(this.toString() + " is expired");
	}

}


AddListenerDemo.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 AddListenerDemo {

	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().expiration(5, TimeUnit.SECONDS)
				.expirationPolicy(ExpirationPolicy.CREATED).build();

		expiringMap.put(1, new Employee(1, "Ram"));
		
		System.out.println(("Adding expiration listener to the ExpiringMap"));
		expiringMap.addExpirationListener((key, employee) -> ((Employee) employee).logOnExpire());
		sleepNSeconds(10);

	}
}


Output

Adding expiration listener to the ExpiringMap

Sleeping for 10 seconds
Employee [id=1, name=Ram] is expired


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment