Tuesday 27 April 2021

Caffeine: Reference based eviction

 

In Caffeine, we can configure a cache with WeakRefence for both keys and values, and we can configure the SoftReference for values.

 

Example

Cache<Integer, Employee> weakCache = Caffeine.newBuilder().weakKeys().weakValues().build();

Cache<Integer, Employee> softCache = Caffeine.newBuilder().softValues().build();

 

What is weak reference?

If an object has only weak references associated with it, then Garbage collector permitted to reclaim the memory used by the object. Weak References to an object are created using WeakReference class.

 

Example

WeakReference<Employee> weakRef1 = new WeakReference<>(new Employee(1, "Krishna", "Gurram", 5l));

 

Reference

https://self-learning-java-tutorial.blogspot.com/2014/07/weak-reference-in-java.html

 

What is soft reference?

An object which is not strongly reachable and and can be accessed through a soft reference is called softly reachable object. All the soft reachable objects will be cleared before JVM throws OutOfMemoryError. In simple terms, Garbage collector clears the Softly reachable objects when memory is needed.

 

Reference

https://self-learning-java-tutorial.blogspot.com/2014/07/soft-reference-in-java.html

https://self-learning-java-tutorial.blogspot.com/2014/07/using-soft-reference-for-caching.html

 

 

Find the below working application.

 

Employee.java 

package com.sample.app.model;

public class Employee {

	private int id;
	private String firstName;
	private String lastName;
	private long expiryTime;

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

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

	public long getExpiryTime() {
		return expiryTime;
	}

	public void setExpiryTime(long expiryTime) {
		this.expiryTime = expiryTime;
	}

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

}

 

App.java

package com.sample.app;

import java.lang.ref.WeakReference;
import java.util.Map;

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

public class App {

	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> weakCache = Caffeine.newBuilder().weakKeys().weakValues().build();

		WeakReference<Employee> weakRef1 = new WeakReference<>(new Employee(1, "Krishna", "Gurram", 5l));
		WeakReference<Employee> weakRef2 = new WeakReference<>(new Employee(2, "Gopi", "Battu", 8l));
		WeakReference<Employee> weakRef3 = new WeakReference<>(new Employee(3, "Saurav", "Sarkar", 15l));

		System.out.println("Attached soft reference to employee1");
		Employee emp = weakRef1.get();

		weakCache.put(1, weakRef1.get());
		weakCache.put(2, weakRef2.get());
		weakCache.put(3, weakRef3.get());

		printCache(weakCache);

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

		printCache(weakCache);

	}

}

 

Output

Attached soft reference to employee1
Elements in the cache are
Employee [id=2, firstName=Gopi, lastName=Battu, expiryTime=8]
Employee [id=3, firstName=Saurav, lastName=Sarkar, expiryTime=15]
Employee [id=1, firstName=Krishna, lastName=Gurram, expiryTime=5]

Perform garbage collection

Performing cleanup operations

Elements in the cache are
Employee [id=1, firstName=Krishna, lastName=Gurram, expiryTime=5]

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment