¿Cuál es la mejor manera de almacenar en caché un solo objeto dentro de un tiempo de espera fijo?


Google Guava tiene CacheBuilder que permite crear ConcurrentHash con claves caducadas que permiten eliminar entradas después del tiemout fijo. Sin embargo, necesito almacenar en caché solo una instancia de cierto tipo.

¿Cuál es la mejor manera de almacenar en caché un solo objeto dentro del tiempo de espera fijo utilizando Google Guava?

 40
Author: Alexey Zakharov, 2011-10-23

1 answers

Usaría los Proveedores de Guayaba .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();
            }
        };
    }
}

Actualización con JDK 8

Hoy, escribiría este código de manera diferente, usando referencias de método JDK 8 e inyección de constructor para código más limpio:

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();
    }
}
 87
Author: Etienne Neveu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-21 17:26:53