Tuesday, 20 April 2021

Guava cache: Get all the entries in cache

Cache interface provides asMap method, using this we can get a view of the entries stored in this cache as a thread-safe map.

 

Signature

ConcurrentMap<K, V> asMap()

 

Example

ConcurrentMap<Integer, Employee> map = empCache.asMap();

 

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

}

 

HelloWorld.java

package com.sample.app.cache;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.sample.app.cache.model.Employee;

public class HelloWorld {

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

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

		empCache.put(1, new Employee(1, "Krishna", "Gurram"));
		empCache.put(2, new Employee(2, "Ramadevi", "Amara"));

		ConcurrentMap<Integer, Employee> map = empCache.asMap();
		Set<Map.Entry<Integer, Employee>> entrySet = map.entrySet();

		for (Map.Entry<Integer, Employee> entry : entrySet) {
			System.out.println(entry.getKey() + " -> " + entry.getValue());
		}
	}

}

Output

2 -> Employee [id=2, firstName=Ramadevi, lastName=Amara]
1 -> Employee [id=1, firstName=Krishna, lastName=Gurram]

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment