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


net.jodah
expiringmap
0.4.0

Example:

//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)
.build();
//Objects can to expire by its last access
Map<String, Connection> map = ExpiringMap.builder()
.expirationPolicy(ExpirationPolicy.ACCESSED)
.expiration(5, TimeUnit.MINUTES)
.build();
//You can do individual configuration
Map<String, String> map = ExpiringMap.builder()
.variableExpiration()
.build();

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);
map.resetExpiration("foo");
//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) {
connection.close();
})
.build();

Take a look on the oficial project link bellow:
https://github.com/jhalterman/expiringmap