Reputation: 4607
I have a Servlet that communicates with an EJB to pull a list of products from my database. This operation is fairly quick (5 secs), but the list of products in the database don't change that often, so I started to think that maybe I should implement some sort of time based caching mechanism, so that I don't go to the database every time someone hits my Servlet if I don't need to.
To just take a shot at it, in the Servlets init method, I initialize a global long variable (lastUpdateTime) to be the current system time. I also have a global variable that references an arraylist of products(allProducts).
When my Servlets doGet() method is called, I use a method called shouldRefreshData(), whose return value I use to determine if I should make a call to my ejb to go off and get the products.
The shouldRefreshData() method basically does 2 things:
-checks to see if the array list of products is null (returns true in this case)
-checks to see if the time difference between the current time and the lastUpdateTime is greater than some time (1 minute for my testing, and if so, return true)
-otherwise, return false
I then use the results of shouldRefreshData() as follows:
if(shouldRefreshData()) {
allProducts = productManager.getProducts();
lastUpdateTime = System.currentTimeMillis();
}
I tested the code, and it's working great, but my question is, since I'm fairly new to web development, can anyone see any drawbacks to my approach.
Second, are there patterns out there for doing time based caching that may be more efficient than the approach that I'm taking? Or better yet, a mechanism that allows me to say here is the data that I have, and if the data in the database is different, then update.
Thank you for your input.
Upvotes: 0
Views: 568
Reputation: 3414
This will work, but it has the disadvantage that you have to clean out the cache yourself.
If you want to get out of manual cache management, you could deploy a caching library like infinispan or ehcache.
If you don't want to take the time to set up (yet another) 3rd party library, you could always do something like this:
@Singleton
public class CacheResource {
public void put(String key, Object value) { /* snip */ }
public void get(String key) { /* snip */ }
/* snip ... */
@Schedule(hour="*", minute="∗/5")
public void clearCache() { /* snip */ }
}
This will create a cache resource that is a singleton bean that will clear itself every 5 minutes. You're still managing the cache yourself, but it isn't tied to one application and you don't have to worry about clearing the cache on time. It also means another EJB deployed to your container which you may not want to do.
Cheers!
Upvotes: 1
Reputation: 73578
Rather than writing your own, I would recommend you employ a proper second level cache solution such as EHCache
. That way you can implement caching on other parts as well.
Upvotes: 1