2
1
|
I am storing data in application scope. I want to clear this data after every hour. Infact using it as cache for one hour. What is the best way to implement this? Earlier we used session scope to store this data and it used to get expired after session gets expired. As this data is unique across the application we want to store it in application scope.
| |||
add comment |
4
|
For a very simple cache you can use the Google guava's MapMaker: Here is the example taken from the javadoc:
there are these two methods expireAfterWrite and expireAfterRead to do what yuo want. And for free you have a thread safe Map, with weakValue, softkeys and lazy evaluation if you want/need it :)
| ||||||||||||
|
1
|
Depending on whether you want to aggressively clear expired data (to recover memory) or you just want to recompute after expiration time, the approach would be very different.
If you simply want to recompute, I would extend SoftReference, for example:
If you want to aggressively reclaim memory, you need to implement a sort of garbage collection. The approach to take is to first put all references in a threadsafe priority queue, then occasionally peek at the first element, to see if at least one of the references have expired:
You will need to call tick() on the queue every couple of seconds or whatever. To do that in Java EE, you will need to use a timer service or something like that.
| |||
add comment |
0
|
Where is this data coming from? If from a DB, you should consider using an ORM with support for first and second level caches like Hibernate/JPA. This way you don't need to change your code in order to be dependent from the cache (which would make it pretty hard maintainable/reusable). You just fire SQL queries the usual way and Hibernate/JPA will return objects from Java's in-memory cache whenever applicable.
See also: | ||
add comment |
0
|
We found a way to clear application scope variables using ServletContextListener and Timer.
Add Listener in web.xml
| ||
add comment |