views:

49

answers:

2

What is the best way to make threadsafe HashMap in Tomcat ?I'm going to create ConcurrentHashMap on InitServlet once on load on my application.

 (<load-on-startup>1</load-on-startup>)

Requests from different threads will read and write data to my ConcurrentHashMap. I'm not good in mutlithreading, so not sure is it approach correct?

And where is the best place to put this HashMap should i make it static ?

Thank you

+4  A: 

Don't make it static - put it in the ServletContext via ctx.setAttribute("mapAttrKey", map). Otherwise it's fine. However it is not very common to do things like this, so please share your use-case - there might be a more proper solution.

Bozho
+3  A: 

If the "initServlet" does nothing else than webapplication initialization, then you'd rather prefer a ServletContextListenrer. Here's a kickoff example:

public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }

}

Register it in web.xml as follows:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

That's it. You could keep of the Map as an instance variable and/or store it in the ServletContext (the application scope).

Related questions:

BalusC
+1 for the ServletContextListener
Bozho