Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to build a non-blocking cache by Guava cache

Shulou Source: shulou.com Published: 2022-06-02 07:34:26 10月03日 Update

This article focuses on "how to build a non-blocking cache in Guava cache". Interested friends may wish to take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to build a non-blocking cache in Guava cache.

Guava cache builds a non-blocking cache for scenarios:

Guava cache is a local cache and is implemented based on JDK ConcurrentHashMap. It is not suitable for use in a distributed environment (unless its node cache consistency can be guaranteed, such as: open source J2cache in the open source Chinese community). If the scenario is simple and there is no need to use the cache complexity feature, you can use ConcurrentHashMap, which is more efficient and direct than Guava cache.

Construction method:

There are three ways to build: CacheLoader,Callable,Inserted Directly.

CacheLoader:

Suitable for having some reasonable default functions to load or calculate key-related values

Callable:

If you need to override the default value, but still need atomic "get-if-absent-compute" semantics, you should use the get method to pass the Callable interface. Implemented: if cached, return; otherwise create, cache and return.

Inserted Directly:

Insert values directly using put.

CacheLoader builds a non-blocking cache:

/ * * Custom refresh cache thread pool * /

Private static ListeningExecutorService backgroundRefreshPools =

MoreExecutors.listeningDecorator (executorService)

/ * * create cache * /

Public static final LoadingCache cache = CacheBuilder.newBuilder ()

.refreshAfterWrite (100no TimeUnit.MILLISECONDS)

.build (new CacheLoader () {)

@ Override

Public String load (String key) {

Return getNewValue ()

}

@ Override

Public ListenableFuture reload (String key,String oldValue) {

Return backgroundRefreshPools.submit (ReloadCache::getNewValue)

}

});

Source code:

Public ListenableFuture loadFuture (K key, CacheLoader)

Tags: Caching blocking entries queries methods methods conditions threads content functions scenarios actual learning complex practical deeper consistent necessary consistent items Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Apple Shulou Tech Info Shulou Technology macOS