Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best place to store large data retrieved by a java servlet (Tomcat)

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?

like image 443
Tatyana Maximovskaya Avatar asked Dec 21 '22 23:12

Tatyana Maximovskaya


2 Answers

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.

like image 43
BalusC Avatar answered Dec 28 '22 06:12

BalusC


Put it in ServletContext But use ConcurrentHashMap to avoid concurrency issues.

like image 129
Bozho Avatar answered Dec 28 '22 07:12

Bozho