Best Place to Store Big Data Retrieved Using the Java Servlet (Tomcat)

I have a Java servlet that retrieves data from a mysql database. To minimize callbacks to the database, it is retrieved only once in the init () method and placed in the HashMap <> (i.e., Cached in memory).

Now this HashMap is a member of the servlet class. I need to not only store this data, but also update some values ​​(actually counters) in cached objects of the base class of hashmap values. And there is a Timer (or Cron task) to schedule the reset of these counters in the DB.

So, after googling, I found 3 options for storing cached data:

1), as now, as a member of the servlet class (but servlets can be decommissioned and returned to operation by the container at will, and then the data will be lost)

2) in ServletContext (is it true that it is recommended to store small amounts of data here?)

3) in the JNDI resource.

What is the most preferred way?

+4
source share
4 answers

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

+5
source

Of these 3 options, it is best to save it in the application area. That is, use ServletContext#setAttribute() . For this you want to use ServletContextListener . In regular servlets, you can access the ServletContext inherited getServletContext() method. In JSP, you can access ${attributename} .

If the data gets excessively large that it consumes too much Java memory, then you should consider the fourth option: use a cache manager.

+3
source

The most obvious way is to use something like ehcache and store the data in it. ehcache is a cache manager that works just like a hash map, except that the cache manager can be configured to store things in memory, move them to disk, hide them, even write them to the database via the plugin and etc. It depends if the objects are serialized, and whether your application can cope without data (i.e. make another trip there, if necessary), but I would trust the cache manager to handle this better than a manual solution.

+2
source

If your cache can become large enough and you often access it, it is wise to use some caching solution. For example, ehcache is a good candidate and integrates easily with Spring applications. The documentation is here .

Also check out this overview of open source caching solutions for Java.

+1
source

All Articles