I need a data structure that runs a piece of code after the the key-value pair expires. For example, I have a key and a connection Object stored in the expiring hashmap. I need this expiring hashmap to run a function that takes the takes connObj as argument and closes the connection after the key-value pair has expired.
I have explored PassiveExpiringMap by Apache and Guava.MapMaker by Google but I don't see any cleanup functionality, does anyone know of any way to do this?
After exploring, I found this expiring hashmap by Jodah quite helpful - https://jodah.net/expiringmap/javadoc/net/jodah/expiringmap/ExpiringMap.html
The data structure uses an asynchronous expiration listener. My implementation was something like this
Map<String, Connections> ConnMap = ExpiringMap.builder()
.maxSize(100000)
.expiration(30, TimeUnit.MINUTES)
.expirationPolicy(ExpirationPolicy.ACCESSED)
.expirationListener((key, connObject) -> {
System.out.println("Closing connObject->key: " + key + " connObj: " + connObject);
connObject.close();
})
.build();