How does Tomcat create threads internally?

∥☆過路亽.° 提交于 2020-01-03 03:30:09

问题


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.


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/28776332/how-does-tomcat-create-threads-internally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!