For example, Redis allows you to specify an expiration date for an entry. That's generally enough, but look for a collection library in Java that can do that.
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.0-jre</version>
</dependency>
</dependencies>
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections4.map.PassiveExpiringMap;
public class App {
public static void main(String[] args) throws InterruptedException {
Map<String, String> map = new PassiveExpiringMap<String, String>(3000, TimeUnit.MILLISECONDS);
map.put("key1", "value1");
while (true) {
TimeUnit.MILLISECONDS.sleep(1000);
System.out.println(map.size());
}
}
}
When the above is executed, it becomes as follows.
1
1
0
Expiration date 3 seconds. Expiration is not checked unless you perform a specific operation on the map as `Passive`
. What is a specific operation? ```All expired entries are removed from .. as shown in https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/PassiveExpiringMap.html The one with .`` `or something written on it.
note that passiveexpiringmap is not synchronized and is not thread-safe
It is written that you need to be careful there.
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class GuavaCaamain {
public static void main(String[] args) throws InterruptedException {
Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(3000, TimeUnit.MILLISECONDS).build();
cache.put("key1", "value1");
while (true) {
TimeUnit.MILLISECONDS.sleep(1000);
cache.put("key2", "value2");
System.out.println(cache.size());
}
}
}
When the above is executed, it becomes as follows.
2
2
1
Check the expiration date at the time of writing as shown in expireAfterWrite </ code>. So if you delete the put line from the above code, the cache contents will not change.
On the contrary, to check at the time of reading, follow the steps below.
Cache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(3000, TimeUnit.MILLISECONDS).build();
https://stackoverflow.com/questions/3802370/java-time-based-map-cache-with-expiring-keys
Recommended Posts