gpt4 book ai didi

java - Servlet "has started a thread but failed to stop it"- Tomcat 内存泄漏

转载 作者:太空狗 更新时间:2023-10-29 22:55:16 24 4
gpt4 key购买 nike

Apache Tomcat 说了很多次:

The web application [/MyServlet] appears to have started a thread named [pool-61-thread-2] but has failed to stop it. This is very likely to create a memory leak.

这很危险吗? servlet 应该能够处理 10.000 个请求/天。如何在完成后关闭线程?

class Worker {

private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
private final int threadNumber;

Worker(
CountDownLatch startSignal,
CountDownLatch doneSignal,
int threadNumber
){

this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.threadNumber = threadNumber;

}

public String[][] getSomeStrArrArr() {

String[][] isRs = new String[8][20];
String[][] inRs = new String[8][20];
String[][] iwRs = new String[8][20];

try {

startSignal.await();

if (threadNumber == 1) {
// get String[][] result for thread number 1
isRs = getIS(erg1, erg2, request);

}

if (threadNumber == 2) {
// get String[][] result for thread number 2
inRs = getIN(search_plz, request);
}

if (threadNumber == 3) {
// get String[][] result for thread number 3
iwRs = getIW(erg1, erg2, request);
}

doneSignal.countDown();

} catch (InterruptedException ex) {

System.out.println(
"Thread number "+threadNumber+" has been interrupted."
);

}
if (threadNumber == 1) {
return isRs;
}
if (threadNumber == 2) {
return inRs;
}
if (threadNumber == 3) {
return iwRs;
}
return null;
}


public Callable<String[][]> getSomeCallableStrArrArr(){
return new Callable<String[][]>() {
public String[][] call() throws Exception {
return getSomeStrArrArr();
}
};
}

}

ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<String[][]>> set = new HashSet<Future<String[][]>>();
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(3);
for (int i=1;i<=3;i++) {
Worker worker = new Worker(startSignal,doneSignal,i);
Callable<String[][]> callable =
worker.getSomeCallableStrArrArr();
Future<String[][]> future = pool.submit(callable);
set.add(future);
}
startSignal.countDown();
try {
doneSignal.await();

最佳答案

是的,这是一个问题。如果您的代码启动非守护线程,那么这些线程将继续工作,直到它们退出 run 方法。即使其他一切都完成了,旧的 JVM 也会在这些线程继续运行时挂起。如果您启动一个新实例,那么您可能会遇到旧线程仍在与新实例创建的线程一起工作的情况。

需要设计任务,以便它们能够响应中断(而不是吃掉异常并继续,这就是您的示例所显示的)。这意味着检查当前线程上的中断标志,并以一种有用的方式捕获 InterruptedException,从而允许任务中断其工作并在需要时重置中断标志。 ExecutorService 实现有一个 shutdownNow 方法,它会中断当前任务。

Here's an example of how to stop a thread using interruption .

确保执行器被关闭,you can handle this in a ServletContextListener .

关于java - Servlet "has started a thread but failed to stop it"- Tomcat 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com