Tuesday, 27 April 2021

Caffeine: Get age of element in the cache

Cache interface provides getPolicy method to inspect and perform low-level operations based on the cache's runtime characteristics.

Example

private static void printAgeOfEntryUsingAfterWritePolicy(Cache cache, Object key) {
	Optional<FixedExpiration> expirationPolicy = cache.policy().expireAfterWrite();

	if (!expirationPolicy.isPresent()) {
		return;
	}

	Optional<Duration> ageOfEntry = expirationPolicy.get().ageOf(key);
	if (!ageOfEntry.isPresent()) {
		return;
	}

	Duration duration = ageOfEntry.get();

	System.out.println("Element with key " + key + " is in the cache from " + duration.getSeconds() + " seconds....");
}

 

Above snippet print the age of an entry using after write policy.

 

Find the below working application.

 

Employee.java

 

package com.sample.app.model;

public class Employee {

	private int id;
	private String firstName;
	private String lastName;

	public Employee(int id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
	}

}

 

App.java

package com.sample.app;

import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Policy.FixedExpiration;
import com.sample.app.model.Employee;

public class App {

	private static void printCache(Cache cache) {
		System.out.println("\nElements of cache are");
		Map map = cache.asMap();

		for (Object key : map.keySet()) {
			System.out.println(map.get(key));
		}
	}

	private static void printAgeOfEntryUsingAfterWritePolicy(Cache cache, Object key) {
		Optional<FixedExpiration> expirationPolicy = cache.policy().expireAfterWrite();

		if (!expirationPolicy.isPresent()) {
			return;
		}

		Optional<Duration> ageOfEntry = expirationPolicy.get().ageOf(key);
		if (!ageOfEntry.isPresent()) {
			return;
		}

		Duration duration = ageOfEntry.get();

		System.out.println("Element with key " + key + " is in the cache from " + duration.getSeconds() + " seconds....");
	}

	public static void main(String args[]) throws InterruptedException {
		Cache<Integer, Employee> cache = Caffeine.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).recordStats().build();

		Employee emp1 = new Employee(1, "Krishna", "Gurram");
		Employee emp2 = new Employee(2, "Gopi", "Battu");
		Employee emp3 = new Employee(3, "Saurav", "Sarkar");

		cache.put(emp1.getId(), emp1);
		TimeUnit.SECONDS.sleep(2);
		
		cache.put(emp2.getId(), emp2);
		cache.put(emp3.getId(), emp3);

		System.out.println("Inserted 3 entries into the cache");
		printCache(cache);
		
		printAgeOfEntryUsingAfterWritePolicy(cache, emp1.getId());
		printAgeOfEntryUsingAfterWritePolicy(cache, emp2.getId());
		printAgeOfEntryUsingAfterWritePolicy(cache, emp3.getId());

		System.out.println("\nSleeping for 3 seconds");
		TimeUnit.SECONDS.sleep(3);
		
		cache.cleanUp();
		
		printAgeOfEntryUsingAfterWritePolicy(cache, emp1.getId());
		printAgeOfEntryUsingAfterWritePolicy(cache, emp2.getId());
		printAgeOfEntryUsingAfterWritePolicy(cache, emp3.getId());

	}

}

 

Output

Inserted 3 entries into the cache

Elements of cache are
Employee [id=1, firstName=Krishna, lastName=Gurram]
Employee [id=2, firstName=Gopi, lastName=Battu]
Employee [id=3, firstName=Saurav, lastName=Sarkar]
Element with key 1 is in the cache from 2 seconds....
Element with key 2 is in the cache from 0 seconds....
Element with key 3 is in the cache from 0 seconds....

Sleeping for 3 seconds
Element with key 2 is in the cache from 3 seconds....
Element with key 3 is in the cache from 3 seconds....

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment