Sunday 3 October 2021

ExpiringMap: Expire the entry by last accessed time

'ExpirationPolicy.ACCESSED' 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.ACCESSED).build();

 

In the above example, I defined ExpiringMap with ACCESSED expiration policy and set the expiration time to 10 seconds. That means, if you do not access the entry in last 10 seconds, it will get expired and removed from the cache.

 

Let’s confirm it with an example.

 

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

}

AccessedExpirationPolicyDemo

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

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

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

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

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

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

		sleepNSeconds(11);
		System.out.println("Since we are not accessed the entry for last 10 seconds, entry gets removed");
		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 5 seconds
Entry with key 1 -> Employee [id=1, name=Krishna]

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

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

Sleeping for 11 seconds
Since we are not accessed the entry for last 10 seconds, entry gets removed
Entry with key 1 -> null



  

Previous                                                    Next                                                    Home

No comments:

Post a Comment