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 set the map of expiration time for Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how Java sets the expiration time of map. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

I. Technical background

In the actual project development, we often use cache middleware (such as redis, MemCache, etc.) to help us improve the usability and robustness of the system.

But in many cases, if the project is relatively simple, it is not necessary to introduce middleware such as Redis to increase the complexity of the system. Does Java itself have a lightweight caching component that works well?

The answer, of course, is yes, and there is more than one way. There are three common solutions: ExpiringMap, LoadingCache and HashMap-based packaging.

II. Technical effect

Implement common functions of caching, such as obsolete delete policies

Hot spot data preheating

III. Brief introduction of ExpiringMap3.1 function

You can set the Entry in Map to expire automatically after a period of time.

The maximum capacity value of Map can be set, and when the Maximum size is reached, inserting the value again will cause the first value in the Map to expire.

You can add a listening event to schedule the listening function when the listening Entry expires.

You can set lazy loading to create an object when the get () method is called.

3.2 Source Code

Github address

3.3 exampl

Add dependency (Maven)

Net.jodah expiringmap 0.5.8

Sample source code

Public class ExpiringMapApp {public static void main (String [] args) {/ / maxSize: set the maximum value. When you add the 11th entry, it will cause the first one to expire immediately (even if it does not reach the expiration time) / / expiration: set the validity time of each key for 10s. If the key does not set the expiration time, the key will be valid forever. / / variableExpiration: the expiration time value is allowed to be updated. If variableExpiration is not set, the expiration time is not allowed to be changed later. Once the operation of changing the expiration time is performed, an exception will be thrown UnsupportedOperationException / / policy: / / CREATED: zero expiration time only in put and replace methods / / ACCESSED: increase on the basis of CREATED policy, and get method will clear zero expiration time before expiration. / / to clear the expiration time is to reset the expiration time and recalculate the expiration time. ExpiringMap map = ExpiringMap.builder () .maxSize (10) .Expiration (10, TimeUnit.SECONDS) .variableExpiration (). ExpirationPolicy (ExpirationPolicy.CREATED). Build (); map.put ("token", "lkj2412lj1412412nmlkjl2n34l23n4"); map.put ("name", "Administrator", 20000, TimeUnit.SECONDS); / / simulated thread waiting. Try {Thread.sleep (15000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("token = >" + map.get ("token"); System.out.println ("name = >" + map.get ("name")) / / Note: when creating a map, the specified parameters such as expiration time and expiration policy are global and apply to every entry added to the map. / / when you put an entry key-value pair, you can set the expiration time and expiration policy separately for the current entry, which is only valid for the current entry. }}

Running result

Token = = > null

Name = > Administrator

Be careful

When you create a map, the parameters you specify, such as expiration time and expiration policy, are global and apply to every entry added to the map.

When you put an entry key-value pair, you can set the expiration time and expiration policy separately for the current entry, which is only valid for the current entry.

IV. Brief introduction of LoadingCache4.1 function

Google is an open source thread-safe local caching solution.

Features: provide cache recovery mechanism, monitor cache load / hit situation, flexible and powerful function, simple and easy to use api.

4.2 exampl

Source code

Public class LoadingCacheApp {public static void main (String [] args) throws Exception {/ / maximumSize: cache pool size, when the cache entry approaches this size Guava starts to recycle old cache items / / expireAfterAccess: set time objects are not read / write accessed, then objects are deleted from memory (maintained irregularly in another thread) / / removalListener: remove listeners Hook / / recordStats triggered when the cache entry is removed: enable the statistical function of Guava Cache LoadingCache cache = CacheBuilder.newBuilder () .maximumSize (100) .accepreAfterAccess (10 TimeUnit.SECONDS) .removalListener (new RemovalListener () {@ Override public void onRemoval (RemovalNotification removalNotification) {System.out.println ("obsolete deleted hook triggers.. Key = = > "+ removalNotification.getKey ();}}) .recordStats () .build (new CacheLoader () {/ / processing the processing logic when the cache key does not have a cache value @ Override public String load (String key) throws Exception {return" non-existent key ") }}); cache.put ("name", "Xiaoming"); cache.put ("pwd", "112345"); / / simulated thread waiting. Try {Thread.sleep (15000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("token = >" + cache.get ("name")); System.out.println ("name = >" + cache.get ("pwd"));}}

Running result

The obsolete deleted hook triggered. Key = = > name

Token = = > key that does not exist

The obsolete deleted hook triggered. Key = = > pwd

Name = = > key that does not exist

4.3 removal mechanism

When guava does cache, there are two types of data removal: passive removal and active removal.

Passive removal

Size-based removal: if the number reaches the specified size, the less commonly used key values will be removed

Time-based removal: expireAfterAccess (long, TimeUnit) removes after the last access based on a key value. ExpireAfterWrite (long, TimeUnit) is removed based on how long a key-value pair is created or the value is replaced

Reference-based removal: mainly based on the garbage collection mechanism of java, which is decided to remove according to the reference relationship of keys or values.

Active removal

Remove separately: Cache.invalidate (key)

Bulk removal: Cache.invalidateAll (keys)

Remove all: Cache.invalidateAll ()

If the remove listener RemovalListener is configured, the logic under that listener is executed synchronously when all removed actions are performed.

To change it to asynchronous, use: RemovalListeners.asynchronous (RemovalListener, Executor).

4.4 other

Before the put operation, if the key value already exists, removalListener will be triggered to remove the listener before adding

ExpireAfterAccess and expireAfterWrite are configured, but are not removed after the specified time.

Delete policy logic:

The cache built by CacheBuilder does not automatically perform cleanup and recycling at a specific time, nor does it clean up immediately after a cache entry expires, and it does not start a thread for cache maintenance, because first the thread is relatively heavy, and secondly, some environments restrict thread creation.

It does a small amount of maintenance work incidentally during write operations, or occasionally during read operations. Of course, you can also create your own maintenance thread to call Cache.cleanUp () at regular intervals.

Thank you for reading! This is the end of this article on "how to set the expiration time map of Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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

Development

Wechat

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

12
Report