【发布时间】:2019-12-20 18:31:20
【问题描述】:
我正在开发一个使用static 工作流加载一次性缓存的模块。缓存加载通常需要大约一个小时。为了提高性能,我正在考虑使用线程池并行运行这些任务。这是示例代码。
应用启动类:
public class AppStart {
public static void main(String[] args) {
Cache.isValid(); // this will trigger the static workflow
// ...
}
}
缓存加载器类:
public class Cache {
static {
System.out.println("Static block initialization started!");
initialize();
System.out.println("Static block initialization finished!");
}
public static void initialize( ) {
System.out.println("initialize() started!");
ExecutorService executorService = Executors.newSingleThreadExecutor(); // will replace with fixedThreadPool
Future<String> future = executorService.submit(() -> "Hello world!");
System.out.println("Retrieve the result of the future");
String result = null;
try {
result = future.get();
System.out.println(result);
} catch( InterruptedException e ) {
e.printStackTrace();
} catch( ExecutionException e ) {
e.printStackTrace();
}
executorService.shutdown();
}
public static boolean isValid( ) {
return true;
}
}
但是,在上述情况下,阻塞操作future.get 将被永远阻塞,即使它只做一个返回字符串的微不足道的任务。
我也尝试过使用ForkJoinPool,但没有运气。
我使用jconsole 监控线程无法检测到任何死锁。为什么它的行为很奇怪?
【问题讨论】:
-
我想看看它为什么失败的解释。但是无论如何阻止类的初始化都是一个坏主意。移除静态块,并在 main() 中显式调用 initialize()。
标签: java future executorservice forkjoinpool