Tuesday, 20 April 2021

Guava: Avoid caching when the values are null

Sometimes you want to avoid the caching of entries, when the values are null. You can achieve this by throwing an exception in the cache loading logic.

CacheLoader<Integer, Employee> cacheLoader = new CacheLoader<Integer, Employee>() {

	@Override
	public Employee load(Integer key) throws Exception {
		Employee emp = EmployeeService.getObject(key);

		if (emp == null) {
			throw new RuntimeException("Object not found with key " + key);
		}
		return emp;
	}

};

Find the below working application.

 

Employee.java

package com.sample.app.cache.model;

public class Employee {
	private Integer id;
	private String firstName;
	private String lastName;

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

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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 + "]";
	}

}


EmployeeService.java

package com.sample.app.cache.service;

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

import com.sample.app.cache.model.Employee;

public class EmployeeService {

	private static Map<Integer, Employee> data = new HashMap<>();

	static {
		data.put(1, new Employee(1, "Krishna", "Gurram"));
		data.put(3, new Employee(3, "Bomma", "Srikanth"));
	}

	public static Employee getObject(Integer key) throws InterruptedException {
		System.out.println("Loading object with id " + key + " from database....");
		TimeUnit.SECONDS.sleep(2);
		return data.get(key);
	}
}


HelloWorld.java

package com.sample.app.cache;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sample.app.cache.model.Employee;
import com.sample.app.cache.service.EmployeeService;

public class HelloWorld {
	private static void printEmployee(Employee emp, Integer id) {
		System.out.println(emp +"\n");
	}

	private static void getAndPrintObjects(LoadingCache<Integer, Employee> empCache, List<Integer> empIds)
			throws ExecutionException {

		for (Integer id : empIds) {
			try {
				Employee emp = empCache.get(id);
				printEmployee(emp, id);
			}catch(Exception e) {
				System.out.println(e.getMessage() + "\n");
			}
			
		}
	}

	public static void main(String args[]) throws InterruptedException, ExecutionException {

		CacheLoader<Integer, Employee> cacheLoader = new CacheLoader<Integer, Employee>() {

			@Override
			public Employee load(Integer key) throws Exception {
				Employee emp = EmployeeService.getObject(key);

				if (emp == null) {
					throw new RuntimeException("Object not found with key " + key);
				}
				return emp;
			}

		};

		LoadingCache<Integer, Employee> empCache = CacheBuilder.newBuilder().maximumSize(500)
				.expireAfterWrite(10, TimeUnit.SECONDS).recordStats().build(cacheLoader);

		System.out.println("Getting employee with ids 1, 2 and 3 from empCache\n");
		getAndPrintObjects(empCache, Arrays.asList(1, 2, 3));

	}

}


Output

Getting employee with ids 1, 2 and 3 from empCache

Loading object with id 1 from database....
Employee [id=1, firstName=Krishna, lastName=Gurram]

Loading object with id 2 from database....
java.lang.RuntimeException: Object not found with key 2

Loading object with id 3 from database....
Employee [id=3, firstName=Bomma, lastName=Srikanth]









 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment