我有以下类(class)
public class MaintanceTools {
public static final ScheduledThreadPoolExecutor THREADSUPERVISER;
private static final int ALLOWEDIDLESECONDS = 1*20;
static {
THREADSUPERVISER = new ScheduledThreadPoolExecutor(10);
}
public static void launchThreadsSupervising() {
THREADSUPERVISER.scheduleWithFixedDelay(() -> {
System.out.println("maintance launched " + Instant.now());
ACTIVECONNECTIONS.forEach((connection) -> {
try {
if ( !connection.isDataConnected() &&
(connection.getLastActionInstant()
.until(Instant.now(), SECONDS) > ALLOWEDIDLESECONDS)) {
connection.closeFTPConnection();
ACTIVECONNECTIONS.remove(connection);
}
} catch (Throwable e) { }
});
System.out.println("maintance finished " + Instant.now());
}, 0, 20, TimeUnit.SECONDS);
}
}
它会遍历所有 FTP 连接(因为我编写了 FTP 服务器),检查连接是否未传输任何数据并空闲一段时间,如果是,则关闭连接。 问题是在中断线程中抛出一些异常后任务永远不会运行。我知道它写在文档中 如果任务的任何执行遇到异常,则后续执行将被抑制。否则,任务只会通过取消或终止执行器来终止。 我有异常(exception),但它被捕获并且不会超出抛出函数。 该函数会抛出 AsynchronousCloseException,因为它卡在了 channel.read(readBuffer); 上。当连接关闭时,抛出并捕获异常。
问题是如何使 THREADSUPERVISER 工作,而不管任何抛出和处理的异常。
调试输出:
- 维护已启动 2017-08-30T14:03:05.504Z//按预期启动并完成
- 维护完成2017-08-30T14:03:05.566Z
- 输出:FTPConnection id:176 220 服务就绪。
- ……
- 输出:FTPConnection id:190 226 文件存储 135 字节。
- 关闭数据套接字:FTP 连接 190,/0:0:0:0:0:0:0:1:1409
- 维护已启动 2017-08-30T14:03:25.581Z//按预期启动并完成
- 维护完成2017-08-30T14:03:25.581Z
- 异步异常读取错误。//出现异常
- 维护已启动 2017-08-30T14:03:45.596Z//已启动,但尚未完成,不再运行
- 输出:FTPConnection id:176 221 超时,关闭控制和数据连接。
- 关闭数据套接字:FTP 连接 176,/0:0:0:0:0:0:0:1:1407
最佳答案
事实证明,问题出在
ACTIVECONNECTIONS.remove(connection);
我遇到了 ConcurrentModifyingException。解决方案http://code.nomad-labs.com/2011/12/09/mother-fk-the-scheduledexecutorservice/工作完美
关于java - ScheduledThreadPoolExecutor 停止执行并捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45966488/