Julias
Julias

Reputation: 5892

how to enhance tomcat thread pool behaviour

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?

Upvotes: 1

Views: 1062

Answers (2)

Pidster
Pidster

Reputation: 618

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

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.

Upvotes: 1

Related Questions