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

后端 未结 1 370
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 14:03

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 inst

1条回答
  •  野的像风
    2021-01-31 14:08

    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 latestJdkVersionCache
                = Suppliers.memoizeWithExpiration(jdkVersionSupplier(), 365, TimeUnit.DAYS);
    
    
        public JdkVersion getLatestJdkVersion() {
            return latestJdkVersionCache.get();
        }
    
        private Supplier jdkVersionSupplier() {
            return new Supplier() {
                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 latestJdkVersionCache;
    
        @Inject
        public JdkVersionService(JdkVersionWebService jdkVersionWebService) {
            this.latestJdkVersionCache = Suppliers.memoizeWithExpiration(
                    jdkVersionWebService::checkLatestJdkVersion,
                    365, TimeUnit.DAYS
            );
        }
    
        public JdkVersion getLatestJdkVersion() {
            return latestJdkVersionCache.get();
        }
    }
    

    0 讨论(0)
提交回复
热议问题