Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create CaffeineCache object using Java?

I am trying to use Caffeine cache. How to create the object for the Caffeine cache using Java? I am not using any Spring for now in my project.

like image 756
Bravo Avatar asked Aug 03 '26 23:08

Bravo


1 Answers

Based on Caffeine's official repository and wiki, Caffeine is a high performance Java 8 based caching library providing a near optimal hit rate. And it is inspired by Google Guava.

Because Caffeine is an in-memory cache it is quite simple to instantiate a cache object.

For example:

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
    .maximumSize(10_000)
    .expireAfterWrite(5, TimeUnit.MINUTES)
    .refreshAfterWrite(1, TimeUnit.MINUTES)
    .build(key -> createExpensiveGraph(key));
  1. Lookup an entry, or null if not found:

    Graph graph = graphs.getIfPresent(key);
    
  2. Lookup and compute an entry if absent, or null if not computable:

    graph = graphs.get(key, k -> createExpensiveGraph(key));

    Note: createExpensiveGraph(key) may be a DB getter or an actual computed graph.

  3. Insert or update an entry:

    graphs.put(key, graph);
    
  4. Remove an entry:

    graphs.invalidate(key);
    

EDIT: Thanks to @BenManes's suggestion, I'm adding the dependency:

Edit your pom.xml and add:

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>1.0.0</version>
</dependency>
like image 181
Gal Dreiman Avatar answered Aug 05 '26 13:08

Gal Dreiman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!