I have the java servlet that retrieves data from a mysql database. In order to minimize roundtrips to the database, it is retrieved only once in init() method, and is placed to a HashMap<> (i.e. cached in memory).
For now, this HashMap is a member of the servlet class. I need not only store this data but also update some values (counters in fact) in the cached objects of underlying hashmap value class. And there is a Timer (or Cron task) to schedule dumping these counters to DB.
So, after googling i found 3 options of storing the cached data:
1) as now, as a member of servlet class (but servlets can be taken out of service and put back into service by the container at will. Then the data will be lost)
2) in ServletContext (am i right that it is recommended to store small amounts of data here?)
3) in a JNDI resource.
What is the most preferred way?
From those 3 options, the best is to store it in the application scope. I.e. use ServletContext#setAttribute()
. You'd like to use a ServletContextListener
for this. In normal servlets you can access the ServletContext
by the inherited getServletContext()
method. In JSP you can access it by ${attributename}
.
If the data is getting excessive large that it eats too much of Java's memory, then you should consider a 4th option: use a cache manager.
Put it in ServletContext
But use ConcurrentHashMap
to avoid concurrency issues.
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