gpt4 book ai didi

java - ScheduledExecutorService 如何处理终止的线程?

转载 作者:行者123 更新时间:2023-11-29 07:24:36 25 4
gpt4 key购买 nike

ScheduledExecutorService 是否负责处理已终止的线程并生成一个新线程?

在下面的示例中,如果我的任何一个线程由于 Error 而终止,线程池大小会发生什么变化?

调试时,我注意到此服务创建的其中一个线程在未打印任何日志语句的情况下被静默终止。在检查 Thread dump 时,我仍然可以看到 32 个线程仍然存在,并且没有一个被阻塞。

public class CacheManager
{

private static class CacheRefresher extends Thread
{
Cache cache;

public CacheRefresher(Cache cache)
{
this(cache);
}

@Override
public final void run()
{

try {
LOG.info("cache is getting refreshed for " + cache.type);
cache.refreshCache();
} catch (Exception e) {
String subject = "Cache refresh failed in BMW";
LOG.log(Level.WARN, subject + ". Exception thrown:", e);
}
}
}

public void refreshCaches(List<cache> caches)
{
ThreadFactory ourThreadFactory =
new NamedThreadFactory("CacheHandler", true);

ScheduledExecutorService scheduleService =
Executors.newScheduledThreadPool(32, ourThreadFactory);
initialDelay = 60;
for (Cache cache : caches) {
service.scheduleWithFixedDelay(new CacheRefresher(cache), initialDelay, 20, TimeUnit.SECONDS);
initialDelay += 2;
cacheContainers.add(cache);
}
}
}

最佳答案

计划任务中未捕获的异常不会导致计划程序的线程终止。但是,它将阻止重新安排失败的任务。请参阅 ScheduledThreadPoolExecutor.html#scheduleWithFixedDelay 的相应文档:

The sequence of task executions continues indefinitely until one of the following exceptional completions occur:

  • [...]

  • An execution of the task throws an exception. In this case calling get on the returned future will throw ExecutionException, holding the exception as its cause.

关于java - ScheduledExecutorService 如何处理终止的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com