java - ScheduledThreadPoolExecutor 停止执行并捕获异常

标签 java exception scheduledexecutorservice

我有以下类(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/

相关文章:

java - 使用特定字符集将 byte[] 转换为 String 时避免创建 'new' String 对象

java - Spring boot security oauth2 从 cookie 中获取 access_token

Java:异常抛出类?

multithreading - 如何在基于servlet的Web应用程序中运行后台任务?

java - Spring-MVC : Scheduled job did not execute

java - 使用 hibernate 连接不同数据库中的两个表

java - Hibernate使用数据库触发器填充主键

java - 将信息添加到 Throwable 而不创建新的 Throwable 的通用方法

c++ - 如果未捕获异常会发生什么?

android - ScheduledExecutorService 在服务内部只运行一次