Monday 4 October 2021

ExpiringMap: Reset expiration time of the entry

Using 'resetExpiration' method, we can reset the expiration time of the entry.

 

Example

expiringMap.resetExpiration(1);

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");
	}

}


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

	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, "Employee" + 1));
		sleepNSeconds(2);

		long expectedExpiration1 = expiringMap.getExpectedExpiration(1);
		System.out.println("Expected expiry time for entry1 " + expectedExpiration1 +  " milli seconds");
		
		expiringMap.resetExpiration(1);
		
		System.out.println("\nResetting the expiration time of the entry 1");

		expectedExpiration1 = expiringMap.getExpectedExpiration(1);
		System.out.println("\nExpected expiry time for entry1 " + expectedExpiration1 +  " milli seconds");
	}
}


Output

Sleeping for 2 seconds
Expected expiry time for entry1 2981 milli seconds

Resetting the expiration time of the entry 1

Expected expiry time for entry1 4999 milli seconds



Previous                                                    Next                                                    Home

No comments:

Post a Comment