如何关闭并行流中使用的线程本地自动关闭?

时间:2018-11-30 13:43:31

标签: java java-8 java-stream

我有一个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?*/
    })
);

2 个答案:

答案 0 :(得分:7)

使用线程的线程死亡后,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);

通常有一个关闭资源而不抛出异常的方法。编年史有一个,其他图书馆也很多。

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

答案 1 :(得分:0)

似乎您要使用某种共享资源。因此,要么不要使用ThreadLocal(因为每个线程都会有自己的实例(或null),而是等到每个任务都完成

ForkJoinTask task=fj.submit(
    () -> myStream.parallel().forEach(e -> {
//whatever
    })
);
task.get()///wait - timeout would be good here
resource.close();// close that shared resource - wraping all of that with try-with-resources woudl work as well

或者只使用序列化代码之类的资源-使用它并在forEach中将其关闭