How to set expiration time map in Java
1. Technical background
In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system.
But many times if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to use cache to increase the complexity of the system. So does Java itself have any useful lightweight caching components?
The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging.
2. Technical effect
Realize common functions of cache, such as outdated deletion strategy
Hot data warm-up
3. ExpiringMap
3.1 Function Introduction
Entries in the Map can be set to automatically expire after a period of time.
You can set the maximum capacity value of the Map. When the Maximum size is reached, inserting a value again will cause the first value in the Map to expire.
You can add listening events and schedule the listening function when the Entry expires.
You can set up lazy loading and create objects when the get() method is called.
3.2 Source code
github address
3.3 Example
Add dependency (Maven)
<dependency> <groupId>net.jodah</groupId> <artifactId>expiringmap</artifactId> <version>0.5.8</version> </dependency>
Example source code
public class ExpiringMapApp { public static void main(String[] args) { // maxSize: 设置最大值,添加第11个entry时,会导致第1个立马过期(即使没到过期时间) // expiration:设置每个key有效时间10s, 如果key不设置过期时间,key永久有效。 // variableExpiration: 允许更新过期时间值,如果不设置variableExpiration,不允许后面更改过期时间,一旦执行更改过期时间操作会抛异常UnsupportedOperationException // policy: // CREATED: 只在put和replace方法清零过期时间 // ACCESSED: 在CREATED策略基础上增加, 在还没过期时get方法清零过期时间。 // 清零过期时间也就是重置过期时间,重新计算过期时间. ExpiringMap<String, String> map = ExpiringMap.builder() .maxSize(10) .expiration(10, TimeUnit.SECONDS) .variableExpiration().expirationPolicy(ExpirationPolicy.CREATED).build(); map.put("token", "lkj2412lj1412412nmlkjl2n34l23n4"); map.put("name", "管理员", 20000, TimeUnit.SECONDS); // 模拟线程等待... try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("token ===> " + map.get("token")); System.out.println("name ===> " + map.get("name")); // 注意: 在创建map时,指定的那些参数如过期时间和过期策略都是全局的, 对map中添加的每一个entry都适用. // 在put一个entry键值对时可以对当前entry 单独设置 过期时间、过期策略,只对当前这个entry有效. } }
Run result
##token ===> nullAttentionname ===> Administrator
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 putting 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.
public class LoadingCacheApp { public static void main(String[] args) throws Exception { // maximumSize: 缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项 // expireAfterAccess: 设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护) // removalListener: 移除监听器,缓存项被移除时会触发的钩子 // recordStats: 开启Guava Cache的统计功能 LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterAccess(10, TimeUnit.SECONDS) .removalListener(new RemovalListener<String, String>() { @Override public void onRemoval(RemovalNotification<String, String> removalNotification) { System.out.println("过时删除的钩子触发了... key ===> " + removalNotification.getKey()); } }) .recordStats() .build(new CacheLoader<String, String>() { // 处理缓存键不存在缓存值时的处理逻辑 @Override public String load(String key) throws Exception { return "不存在的key"; } }); cache.put("name", "小明"); cache.put("pwd", "112345"); // 模拟线程等待... try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("token ===> " + cache.get("name")); System.out.println("name ===> " + cache.get("pwd")); } }
The outdated deletion hook triggered... key ===> name4.3 Removal mechanismWhen guava caches data, there are two types of data removal: passive removal and active removal. Passive removaltoken ===> Non-existent key
The obsolete deletion hook triggered... key ===> pwd
name ===> Non-existent key
- Size-based removal: When the number reaches the specified size, uncommon key values will be removed
- Time-based removal: expireAfterAccess(long, TimeUnit) removes a key-value pair based on the time after the last access. expireAfterWrite(long, TimeUnit) Remove based on the time after a key-value pair is created or the value is replaced
- Reference-based removal: mainly based on Java's garbage collection mechanism. Determine removal based on the reference relationship of the key or value
- Remove individually: Cache.invalidate(key)
- Batch removal: Cache.invalidateAll(keys)
- Remove all: Cache.invalidateAll()
- Before the put operation, if it has With this key value, removeListener will be triggered first to remove the listener, and then
- is configured with expireAfterAccess and expireAfterWrite, but it is not removed after the specified time.
- Delete policy logic:
The above is the detailed content of How to set expiration time map in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
