Shutdown threads
I have a web application deployed on tomcat. In this application are ExecutorService to perform some concurrent execution of t开发者_如何学运维asks. There are also few methods within my application which uses Thread native as shown below to perform concurrent executions.
new Thread(new Runnable() {
public void run() {
//TODO: Perform some CRUD function
}
}).start();
When a form POST is invoked against these method the threads are started and perform function execution as desired. My question is, is this a good design approach, or do I have to close the thread after each session, or do I close the threads when tomcat shuts down for say maintenance. Can someone point me on the right direction please.
do I have to close the thread after each session, or do I close the threads when tomcat shuts down for say maintenance
I did not quite understand this part, but creating random number of new Threads is a bad idea, firstly it is expensive, secondly it is not possible to create arbitrarily large number of threads, sooner or later you will run into out of memory exceptions. Better work with a thread pool.
Creation and starting of new threads is rather expensive operation. If you concerned about performance, employ Executors.newCachedThreadPool
method.
Additionally, if you wouldn't need to worry about thread limit exhaustion in case you using some Executors.newFixedThreadPool
. Note that using this type of executor may cause delays for users should number of users exceed number of threads in pool. However if operation performed by task is short-timed, users hardly notice delay.
There are two problems with this approach:
- Creating a new thread is not cheap. Sharing a pool of threads between client connections is a better approach
- There might be a system imposed limitation on the number of concurrent threads that the JVM can create. Once this limit has reached, new client connections will be rejected.
You can solve these problems by making use of the facilities provided by the java.util.concurrent
package. See this tutorial for details.
精彩评论