Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active July 18, 2022 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rponte/634e60427309c5fc273bb6cf79d4fc8b to your computer and use it in GitHub Desktop.
Save rponte/634e60427309c5fc273bb6cf79d4fc8b to your computer and use it in GitHub Desktop.
Simple CacheStore using Guava Cache
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Component
public class CacheStore {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheStore.class);
private Cache<String, ExpensiveObject> cache;
@PostConstruct
public void initCache() {
/**
* Desafio aqui eh encontrar politica de cache no workload real para:
* 1. maximizar o cache-hit, ideal +90%
* 2. diminuir os ciclos de GC (minors e principalmente fulls)
* 3. permitir funcionamento normal da app e picos de acessos
*/
this.cache = CacheBuilder.newBuilder()
.maximumSize(100_000)
.expireAfterWrite(1, TimeUnit.DAYS)
.build();
}
public Optional<ExpensiveObject> get(String id) {
ExpensiveObject object = cache.getIfPresent(id);
return Optional.ofNullable(object);
}
public void update(String id, ExpensiveObject object) {
LOGGER.info("[CACHE] Putting key '{}' in cache", id);
cache.put(id, object);
}
public void remove(String id) {
LOGGER.info("[CACHE] Removing key '{}' from cache", id);
this.cache.invalidate(id);
}
}
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
@rponte
Copy link
Author

rponte commented Jul 18, 2022

We can use this new lib, ExpiringMap: A high performance, low-overhead, zero dependency, thread-safe ConcurrentMap implementation that expires entries.

ExpiringMap allows you to create a map that expires entries after a certain time period or when a maximum map size has been exceeded:

Map<String, Connection> map = ExpiringMap.builder()
  .maxSize(123)
  .expiration(30, TimeUnit.SECONDS)
  .build();
  
// Expires after 30 seconds or as soon as a 124th element is added and this is the next one to expire based on the expiration policy
map.put("connection", connection);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment