Alexey Zakharov Alexey Zakharov - 1 year ago 150
Java Question

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

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?

Answer Source

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

public class JdkVersionService {

    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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download