ScheduledExecutorService - 任务停止运行 [英] ScheduledExecutorService - Task stops running
问题描述
私有 ScheduledExecutorService 池 = new ScheduledThreadPoolExecutor(20);
我正在执行任务
public void run() {
if (queue.isEmpty()) return;
ArrayDeque<Profile> current = new ArrayDeque<Profile>();
this.queue.drainTo(current, 20);
MySQLStatement statement = this.wrapper.prepare();
while (!current.isEmpty()) {
if (statement.isClosed()) return;
Profile profile = current.poll();
statement.addBatch(profile.getId().toString(), ProfileBuilder.toJson(profile));
}
statement.executeBatchAsync();
}
使用 ScheduledExecutorService
using a ScheduledExecutorService
pool.scheduleAtFixedRate(new VerboseRunnable(runnable = new MySQLRunnable(this)), 250, 50, TimeUnit.MILLISECONDS);
MySQLRunnable 在一些队列已满的情况下运行后停止工作,但当队列为空时,它或多或少会无限运行.
首先我认为停止可能是因为静默捕获的异常,所以我添加了 VerboseRunnable
The MySQLRunnable stops working after some runs with a full queue, but it runs more or less infinite when the queue is empty.
First i thought the stops could be because of silently caught exception, so i added the VerboseRunnable
public void run() {
try {
runnable.run();
} catch (Throwable e) {
System.err.println("Error in runnable!");
e.printStackTrace();
throw new RuntimeException(e);
}
}
但它仍然停止运行.ScheduledFuture 还告诉我该任务既没有完成也没有取消.
But it still stops running. Also the ScheduledFuture tells me that the task is neither done nor cancelled.
任何帮助都会很好.
推荐答案
在使用资源时应始终小心关闭资源,尤其是 I/O 资源,如连接、语句和结果集.在池化环境中,您很容易最终耗尽连接池,随后的任务将最终阻塞,等待可能永远不可用的连接(如果您很幸运,取决于实现等,连接可能会开始几分钟后关闭自己分钟......或更长时间).
You should always be careful to close resources as you use them, especially I/O resources like connections, statements, and result sets. In a pooled environment, you can very easily end up depleting the pool of connections, and subsequent tasks will end up blocking, waiting for a connection that may never be available (if you're lucky, depending on implementation etc, maybe connections will start closing themselves after a few minutes... or longer).
这篇关于ScheduledExecutorService - 任务停止运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!