Storing "look up table"values in servlet context


Web tier: servlets, JSP, Web frameworks: Storing "look up table"values in servlet context

  1. Hi,

    I was wondering whether it was a good idea to keep "llok up table" values such as country codes in the ServletContext so that no of calls to database can be reduced. what are the bad effects of this implementation?

  2. Whenever you want to keep such a reference in memory, you need to take into account a few factors.
    Size of the object - If its a really large object, it might effect the overall application performance.
    Nature of the data - If you expect the data to remain static, it is safe. However, if the values can be modified / updated in the db, then you may be referring to stale values in memory.
  3. This is a very common technique. The only real issue is thread-safe access to the collection. As Preeti suggests, if the data values never change after they are loaded, you will be OK.

    The only other question is how to safely initialize the collection. Most people do so in the init() method of some Servlet. In fact, a common technique is to define an "InitServlet" to perform any initialization needed by the web application (like loading lists into the ServletContext). You can preload this servlet by assigning it a <load-on-startup> value in the web.xml configuration file.