[英]Java - How to make an ExecutorService running inside another ExecutorService not to shutdown when shutdown is invoked on the outer ExecutorService?
我在另一个执行程序服务中运行Executor服务来发送电子邮件。 如果我在外部执行程序上调用shutdown,它正在等待内部执行程序服务关闭,这会严重影响响应时间。
private final ExecutorService blastExecutor = Executors.newFixedThreadPool(20);
private final ExecutorService mailExecutor = Executors.newFixedThreadPool(2);
public void findDealers() {
blastExecutor.execute(new Runnable() {
public void run() {
try {
identifyDealers();
} catch (Exception e) {
}
}
});
blastExecutor.shutdown();
try {
blastExecutor.awaitTermination(30, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}
logger.info("Completed sending request blasts.");
}
public void identifyDealers() {
mailExecutor.execute(new Runnable() {
public void run() {
try {
sendEmail();
} catch (Exception e) {
}
}
});
}
在blastExecutor.shutdown()
它blastExecutor.shutdown()
调用mailExecutor
关闭(?)
这只是一个示例代码,并且在identifyDealers()
方法中发生了很多业务。 如何使sendEmail异步并使blastExecutor.shutdown()
不等待mailExecutor
关闭?
你的假设似乎是错误的, shutdown()
应该只对外部执行器起作用。 它不会关闭任何其他执行程序。
这是一个基于您的代码的小例子:
ExecutorService e1 = Executors.newFixedThreadPool(20);
final ExecutorService e2 = Executors.newFixedThreadPool(2);
e1.execute(new Runnable() {
public void run() {
System.out.println("e1 started");
e2.execute(new Runnable() {
public void run() {
System.out.println("e2 started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("e2 completed");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
});
e1.shutdown();
System.out.println("e1 shut down signal send");
e1.awaitTermination(30, TimeUnit.MINUTES);
System.out.println("e1 terminated");
e2.awaitTermination(30, TimeUnit.MINUTES);
System.out.println("e2 terminated");
应用程序不会终止,它会在e2.awaitTermination
上e2.awaitTermination
,在输出中它也会显示e2
从未收到关闭信号:
e1 started
e1 shut down signal send
e2 started
e1 terminated
e2 completed
如果mailExecutor
确实关闭了,我认为还有其他的东西在你的代码中没有显示。 由于您的代码的基本结构现在看起来,您正在运行单个任务并立即关闭执行程序,这可能意味着您可能甚至不需要blastExecutor
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.