1

I'm writing a Tomcat application which need to maintain some internal states across different requests, so I need share something between different threads created by Tomcat. My question is, if I write code like this, will Map (which is static to the class) be shared between threads created by Tomcat.

public class sessionManager extends HttpServlet {
    private static HashMap<Integer, String> Map;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // logic
    }
}

I guess what I really don't get is how does Tomcat create many threads from a single class.

qweruiop
  • 3,156
  • 6
  • 31
  • 55

2 Answers2

3

My question is, if I write code like this, will Map (which is static to the class) be shared between threads created by Tomcat[?]

Yes. It will be shared across (potentially) multiple threads.

I guess what I really don't get is how does Tomcat create many threads from a single class.

Threads aren't associated to classes. A thread is a sequence of instructions. It represents execution of your code.

Tomcat spawns a number of threads which it uses to handle requests. It will generate a single instance of your sessionManager class. All threads will use this instance to handle the request. They then each have access to the Map field. You'll need to apply your own external synchronization to make it thread safe, as required.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Ok, I see. Fairly clear. Could you point to a reference about __It will generate a single instance of your `sessionManager` class__? – qweruiop Feb 28 '15 at 00:20
  • @bl4ck5un See chapter 2.2 of the [Servlet Specification](http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-eval-oth-JSpec/). – Sotirios Delimanolis Feb 28 '15 at 00:22
0

doesn't really matter how does tomcat create them. maybe new Thread(name). what you are really asking is what is visible to different threads. to learn more google for 'concurrency', 'thread visibility', 'java memory model' or 'Happened-before'.

in your case the field itself will be visible to all your threads. but changes to that field (assigning new map to the field or changes of the content of the map) may not be propagated between threads. you need to use concurrent mechanisms to communicate between threads (synchronized, volatile, concurrent map etc. whatever suits you best)

piotrek
  • 13,982
  • 13
  • 79
  • 165
  • Good point. Actually I'm asking if Tomcat creates a new instance when spawning a thread, or not. Sotirios's answer is pretty clear about this. – qweruiop Feb 28 '15 at 00:29