Cache class provides 'size' method, it returns the approximate number of entries in this cache.
Example
long cacheSize = empCache.size();
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.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"));
long cacheSize = empCache.size();
System.out.println("Approximate number of entries in the cache are : " + cacheSize);
}
}
Output
Approximate number of entries in the cache are : 2
Previous Next Home
No comments:
Post a Comment