1

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
user12384512
  • 3,362
  • 10
  • 61
  • 97

2 Answers2

4

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
  • 588,226
  • 146
  • 1,060
  • 1,140
  • will it not work if you make it static or is it just bad design? Just wondering. – dogbane Jan 07 '11 at 08:28
  • it will probably work. But static has classloaders associated with it, and you don't want to mess there :) – Bozho Jan 07 '11 at 15:30
3

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555