Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache with fixed expiry time in Java

Tags:

java

caching

My Java web application (tomcat) gets all of its data from an SQL database. However, large parts of this database are only updated once a day via a batchjob. Since queries on these tables tend do be rather slow, I want to cache the results.

Before rolling my own solution, I wanted to check out existing cache solutions for java. Obviously, I searched stackoverflow and found references and recommendations for ehcache.

But looking through the documentation it seems it only allows for setting the lifetime of cached objects as a duration (e.g. expire 1 hour after added), while I want an expiry based on a fixed time (e.g. expire at 0h30 am).

Does anyone know a cache library that allows such expiry behaviour? Or how to do this with ehcache if that's possible?

like image 791
Pieter Avatar asked Feb 26 '10 09:02

Pieter


People also ask

What is cache expire time?

By default, each file automatically expires after 24 hours, but you can change the default behavior in two ways: To change the cache duration for all files that match the same path pattern, you can change the CloudFront settings for Minimum TTL, Maximum TTL, and Default TTL for a cache behavior.

How do I expire my cache?

To set output-cache expirations for a page programmatically In the page's code, set the expiration policy for the page on the Cache property of the Response object. If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well.

What is LRU cache Java?

The term LRU Cache stands for Least Recently Used Cache. It means LRU cache is the one that was recently least used, and here the cache size or capacity is fixed and allows the user to use both get () and put () methods. When the cache becomes full, via put () operation, it removes the recently used cache.


2 Answers

EhCache allows you programmatically set the expiry duration on an individual cache element when you create it. The values configured in ehcache.xml are just defaults.

If you know the specific absolute time that the element should expire, then you can calculate the difference in seconds between then and "now" (i.e. the time you add to the cache), and set that as the time-to-live duration, using Element.setTimeToLive()

like image 155
skaffman Avatar answered Sep 30 '22 01:09

skaffman


Do you need a full blown cache solution? You use standard Maps and then have a job scheduled to clear them at the required time.

like image 22
Mark Avatar answered Sep 30 '22 01:09

Mark