Tuesday 27 April 2021

Caffeine: Time based eviction

We can set eviction policy based on time. There are three types of time based evictions possible.

a.   Expire after write: entry is deleted after a time period is passed since the last write occurs

b.   Expire after access: entry is deleted after a time period is passed since the last read or write occurs

c.    Custom Policy: Expiration time is set for each entry separately.

 

Let’s see an example with first two approaches (expire after write and expire after access) in this post. I will explain the custom policy model in my next post.

 

Expire after write

Cache<Integer, Employee> cache = Caffeine.newBuilder().initialCapacity(1).maximumSize(10).expireAfterWrite(5, TimeUnit.SECONDS).build();

 

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

}

 

ExpireAfterWriteDemo.java

package com.sample.app;

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

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

public class ExpireAfterWriteDemo {

	private static void printCache(Cache cache) {
		System.out.println("Elements in the cache are");
		Map map = cache.asMap();

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

	public static void main(String args[]) throws InterruptedException {
		Cache<Integer, Employee> cache = Caffeine.newBuilder().initialCapacity(1).maximumSize(10)
				.expireAfterWrite(5, TimeUnit.SECONDS).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);
		cache.put(emp2.getId(), emp2);
		cache.put(emp3.getId(), emp3);

		printCache(cache);

		System.out.println("\nAbout to sleep for 3 seconds");
		TimeUnit.SECONDS.sleep(3);

		System.out.println("Reinserting entry with key 2");
		cache.put(2, emp2);

		System.out.println("\nAbout to sleep for 3 seconds");
		TimeUnit.SECONDS.sleep(3);

		/*
		 * Since cache eviction is done asynchronously, let's execute pending
		 * maintenance operations needed by the cache
		 */
		System.out.println("\nPerforming cleanup operations\n");
		cache.cleanUp();

		printCache(cache);

	}
}

 

Output

Elements in the cache are
Employee [id=1, firstName=Krishna, lastName=Gurram]
Employee [id=2, firstName=Gopi, lastName=Battu]
Employee [id=3, firstName=Saurav, lastName=Sarkar]

About to sleep for 3 seconds
Reinserting entry with key 2

About to sleep for 3 seconds

Performing cleanup operations

Elements in the cache are
Employee [id=2, firstName=Gopi, lastName=Battu]

 

Expire after access

Cache<Integer, Employee> cache = Caffeine.newBuilder().initialCapacity(1).maximumSize(10).expireAfterAccess(5, TimeUnit.SECONDS).build();

 

Find the below working application.

 

ExpireAfterAccessDemo.java

package com.sample.app;

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

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

public class ExpireAfterAccessDemo {
	private static void printCache(Cache cache) {
		System.out.println("Elements in the cache are");
		Map map = cache.asMap();

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

	public static void main(String args[]) throws InterruptedException {
		Cache<Integer, Employee> cache = Caffeine.newBuilder().initialCapacity(1).maximumSize(10)
				.expireAfterAccess(5, TimeUnit.SECONDS).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);
		cache.put(emp2.getId(), emp2);
		cache.put(emp3.getId(), emp3);

		printCache(cache);

		System.out.println("\nAbout to sleep for 3 seconds");
		TimeUnit.SECONDS.sleep(3);
		
		System.out.println("Accessing entry with key 2");
		cache.getIfPresent(2);
		
		System.out.println("\nAbout to sleep for 3 seconds");
		TimeUnit.SECONDS.sleep(3);

		/*
		 * Since cache eviction is done asynchronously, let's execute pending
		 * maintenance operations needed by the cache
		 */
		System.out.println("\nPerforming cleanup operations\n");
		cache.cleanUp();

		printCache(cache);

	}
}

Output

Elements in the cache are
Employee [id=1, firstName=Krishna, lastName=Gurram]
Employee [id=2, firstName=Gopi, lastName=Battu]
Employee [id=3, firstName=Saurav, lastName=Sarkar]

About to sleep for 3 seconds
Accessing entry with key 2

About to sleep for 3 seconds

Performing cleanup operations

Elements in the cache are
Employee [id=2, firstName=Gopi, lastName=Battu]




 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment