Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to cache single object within fixed timeout?

Tags:

java

guava

Google Guava has CacheBuilder that allows to create ConcurrentHash with expiring keys that allow to remove entries after the fixed tiemout. However I need to cache only one instance of certain type.

What is the best way to cache single object within fixed timeout using Google Guava?

like image 760
Alexey Zakharov Avatar asked Oct 23 '11 06:10

Alexey Zakharov


People also ask

What is a cache loader?

The cache-loader allow to Caches the result of following loaders on disk (default) or in the database.

What is cache map in Java?

A CacheMap is a Map that supports caching. This interface will be eventually replaced by the javax. cache. Cache interface.

What is in memory cache in Java?

But what is “Cache?” A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute. Examples of such data include a result of a query to a database, a disk file or a report. Lets look at creating and using a simple thread-safe Java in-memory cache.


1 Answers

I'd use Guava's Suppliers.memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit)

public class JdkVersionService {      @Inject     private JdkVersionWebService jdkVersionWebService;      // No need to check too often. Once a year will be good :)      private final Supplier<JdkVersion> latestJdkVersionCache             = Suppliers.memoizeWithExpiration(jdkVersionSupplier(), 365, TimeUnit.DAYS);       public JdkVersion getLatestJdkVersion() {         return latestJdkVersionCache.get();     }      private Supplier<JdkVersion> jdkVersionSupplier() {         return new Supplier<JdkVersion>() {             public JdkVersion get() {                 return jdkVersionWebService.checkLatestJdkVersion();             }         };     } } 

Update with JDK 8

Today, I would write this code differently, using JDK 8 method references and constructor injection for cleaner code:

import java.util.concurrent.TimeUnit; import java.util.function.Supplier;  import javax.inject.Inject;  import org.springframework.stereotype.Service;  import com.google.common.base.Suppliers;  @Service public class JdkVersionService {      private final Supplier<JdkVersion> latestJdkVersionCache;      @Inject     public JdkVersionService(JdkVersionWebService jdkVersionWebService) {         this.latestJdkVersionCache = Suppliers.memoizeWithExpiration(                 jdkVersionWebService::checkLatestJdkVersion,                 365, TimeUnit.DAYS         );     }      public JdkVersion getLatestJdkVersion() {         return latestJdkVersionCache.get();     } } 
like image 105
Etienne Neveu Avatar answered Oct 11 '22 04:10

Etienne Neveu