how to enhance tomcat thread pool behaviour

你说的曾经没有我的故事 提交于 2019-12-24 17:43:27

问题


I'm running the java application using tomcat7. I need to store the information per tomcat thread, so I can use the ThreadLocals approach.

In my server.xml the threadpool definition looks like the following:

 <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
    maxThreads="10000" minSpareThreads="2000"/>

I have a class EnhanceThread

public class EnhanceThread extends Thread {
    ...
    @Override
    public void run() {
       SomeThreadLocals.set(data);
       super.run();
     }
}

How can I override the tomcat thread pool definition and make it use use my class? Is there a better approach to threat this problem?


回答1:


You don't need to mess with Tomcat threads for that. Just use the following code:

public class JsonSerializerFactory {
    private static final ThreadLocal<JsonSerializer> JSON_SERIALIZER = 
        new ThreadLocal<JsonSerializer>() {
            @Override 
            protected JsonSerializer initialValue() {
                 return new JsonSerializer();
            }
        };

    public static JsonSerializer get() {
        return JSON_SERIALIZER;
    }
}

Each time you need a serializer, call JsonSerializerFactory.get(), and it will return the thread-local instance, and lazily create it if it doesn't exist yet.




回答2:


The Tomcat Executor is built on top of the java.util.concurrent classes, so you could replace the Tomcat component classes, but I don't think that's a good idea.

If you need to put data into the request scope, there are a number of well defined ways to do it in the Servlet Specification, for example the ServletRequestListener. You could also use a Servlet Filter and selectively add it to only the requests that need it.



来源:https://stackoverflow.com/questions/10671503/how-to-enhance-tomcat-thread-pool-behaviour

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