I would like to have a HashMap<String, String>
, that every day at midnight, the cache will expire.
Please note that it's J2EE solution so multiple threads can access it.
What is the best way to implement it in Java?
Although the other suggestions can work to time the expiration, it is important to note that :
Expiration of the hashmap can be done lazily
i.e. without any monitor threads !
The simplest way to implement expiration is thus as follows :
1) Extend hash map, and create a local nextMidtime (Long) variable, initialized to System.currentTime....in the constructor. This will be set equal to the Next midnight time, in milliseconds...
2) Add the following snippet to the first line of the the "containsKey" and "get" methods (or any other methods which are responsible for ensuring that data is not stale) as follows :
if (currentTime> nextMidTime)
this.clear();
//Lets assume there is a getNextMidnight method which tells us the nearest midnight time after a given time stamp.
nextMidTime=getNextMidnight(System.currentTimeInMilliseconds);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With