Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java cache hashmap expire daily

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?

like image 575
Dejell Avatar asked Dec 06 '11 22:12

Dejell


1 Answers

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);
like image 94
jayunit100 Avatar answered Sep 17 '22 22:09

jayunit100