java - 如何关闭并行流中使用的线程本地自动关闭?
问题描述
我有一个 ThreadLocal 变量。我想这样使用它:
ThreadLocal<AutoCloseable> threadLocal = new ThreadLocal<AutoCloseable>(); // pseudocode
ForkJoinPool fj = new ForkJoinPool(nThreads);
fj.submit(
() -> myStream.parallel().forEach(e -> {
/*I want to use the thread local autocloseable here,
but how do I close it when this parallel processing is done?*/
})
);
解决方案
ThreadLocal 在使用它们的线程死亡后关闭。如果你想控制这个,你需要使用地图。
// do our own thread local resources which close when we want.
Map<Thread, Resource> threadLocalMap = new ConcurrentHashMap<>();
fj.submit(
() -> myStream.parallel().forEach(e -> {
Resource r = threadLocalMap.computeIfAbsent(Thread.currentThread(), t -> new Resource();
// use the thread local autocloseable here,
})
// later once all the tasks have finished.
// close all the thread local resources when the parallel processing is done
threadLocalMap.values().forEach(Utils::closeQuietly);
通常有一种方法可以在不引发异常的情况下关闭资源。Chronicle 有一个,但许多其他库也有。
public static void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ioe) {
// ignore or trace log it
}
}
}
很可能您的项目中已经有一种方法可以做到这一点 https://www.google.co.uk/search?q=public+static+void+closequietly+Closeable
推荐阅读
- python - 如何检查一个列表是否包含在另一个列表中,但要考虑到顺序
- python - 如何在 Python 中使用 tkinter 更改文本框(条目)的字体颜色
- angular-material - 如何创建与材料字体图标对齐的自定义字体图标?
- outlook - 微软团队用户检测
- java - Spring Security 测试@WithMockUser 不起作用
- angular - 应用于 angular-slickgrid 中的树数据网格时,过滤器无法正常工作
- windows - 通过 .bat 文件仅关闭活动应用程序的窗口
- java - java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: 无法初始化组件 [org.apache.catalina.webresources.Jar
- ios - 在 SwiftUI 中使用时,CGAffineTransform 缩放调整大小无法正常工作
- gridview - c# Gridview - 无法在后面的代码中将控件绑定到 RowDataBound