Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a non-blocking cache by Guava cache

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report