Sunday, 3 October 2021

ExpiringMap: Expire the entry by created time

'ExpirationPolicy.CREATED' expiration policy is used to configure the expiration policy to last accessed time.

 

Example

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


Find the below working application.

 

CreatedExpirationPolicyDemo.java

package com.sample.app;

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

import com.sample.app.model.Employee;

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

public class CreatedExpirationPolicyDemo {
	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 {
		Map<Integer, Employee> expiringMap = ExpiringMap.builder().expiration(10, TimeUnit.SECONDS)
				.expirationPolicy(ExpirationPolicy.CREATED).build();

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

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

		sleepNSeconds(6);
		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 6 seconds
Entry with key 1 -> null


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment