Alternative to cache objects in Java

Some times its necessary to do object cache when we have objects that are accessed several times in database.

The goal is not to overload our database with repeated querys and better the response time.

The following example show how you can to do it using the lib ExpiringMap.

Maven dependecy



//The default expire time is 60 seconds after its creation

Map<String, Integer> map = ExpiringMap.create();
map.put("foo", 5);
//If you need you can change the expire time
Map<String, Connection> map = ExpiringMap.builder()
.expiration(30, TimeUnit.SECONDS)
//Objects can to expire by its last access
Map<String, Connection> map = ExpiringMap.builder()
.expiration(5, TimeUnit.MINUTES)
//You can do individual configuration
Map<String, String> map = ExpiringMap.builder()

map.put("foo", "bar", ExpirationPolicy.ACCESSED, 5, TimeUnit.SECONDS);
//The configuration can be changed in execution time
map.setExpiration("foo", 5, TimeUnit.SECONDS);
map.setExpirationPolicy("foo", ExpirationPolicy.ACCESSED);
//You can to create a listner when you key expire and execute some action
Map<String, Connection> map = ExpiringMap.builder()
.expirationListener(new ExpirationListener<String, Connection>() {
public void expired(String key, Connection connection) {

Take a look on the oficial project link bellow: