Expired collection of java

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.

Source code

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>

Passive Expiring Map from Apache Commons Collections

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-safeIt is written that you need to be careful there.

Guava's Cache Builder

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();

reference

https://stackoverflow.com/questions/3802370/java-time-based-map-cache-with-expiring-keys

Recommended Posts

Expired collection of java
☾ Java / Collection
[Java] Comparator of Collection class
Java9 collection
Java Reintroduction-Java Collection
[Java] Overview of Java
[Java] Collection framework
Significance of interface learned from Java Collection
[Java] Contents of Collection interface and List interface
Predicted Features of Java
[Java] Significance of serialVersionUID
Java collection interview questions
NIO.2 review of java
Review of java Shilber
java --Unification of comments
History of Java annotation
java (merits of polymorphism)
A collection of simple questions for Java beginners
NIO review of java
[Java] Three features of Java
Summary of Java support 2018
Java: Use Stream to sort the contents of the collection
Getting Started with Java Collection
About an instance of java
[Java] Mirage-Basic usage of SQL
[Java] Beginner's understanding of Servlet-②
[Java] Practice of exception handling [Exception]
[Java11] Stream Summary -Advantages of Stream-
Basics of character operation (java)
Inclusion judgment of elements of Collection
Java parallelization code sample collection
[Java] Creation of original annotation
4th day of java learning
[Java] Beginner's understanding of Servlet-①
Java end of month plusMonths
[Java] Summary of regular expressions
[Java] Summary of operators (operator)
[Java] Implementation of Faistel Network
Java test code method collection
What is a Java collection?
Android library collection of "Mercariatte"
Summary of Java language basics
[Java] Summary of for statements
Summary of Java Math class
Enumeration of all combinations Java
java (inheritance of is-a principle)
Implementation of gzip in java
Advantages and disadvantages of Java
Benefits of Java static method
[Java] Summary of control syntax
Implementation of tri-tree in Java
Deep copy collection in Java
Summary of java error processing
[Java] Summary of design patterns
[Java] Summary of mathematical operations
[Java] Set structure of collection class (about HashSet and TreeSet)
[Java] Speed comparison of string concatenation
Think of a Java update strategy
[Java] Delete the elements of List
[For beginners] Summary of java constructor
Various methods of Java String class