如果出现问题并且我想重试,是否安全或建议使用相同的Executor重新入队Runnable?

Avi*_*lax 2 java task queueing executors

我刚刚在runnable的run()方法中编写了这段代码:

try {
    dbConnection = MyApp.datasource.getConnection();
} catch (SQLException e) {
    logger.log(Level.SEVERE, "Could not obtain a DB connection! Re-enqueuing this task. Message: " + e.getMessage(), e);
    MyApp.executor.execute(this);
    return;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,如果任务无法获得数据库连接,它应该将自身重新入队,并进入运行之前的队列.

我认为这可能是安全的,但感觉很有趣,我只是想确保没有任何我缺少的东西.

谢谢!

Dar*_*ron 5

就执行者而言,这很好.

但请记住,失败可能会很快发生,然后Executor可能会快速重新运行您的代码.这可能会导致大量CPU烧毁而无法获得结果.

构建强制重试延迟和最大循环计数.