どのように私は、並列ストリームで使用されるスレッドローカルautocloseableを閉じていますか?

ねえ :

私は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?*/
    })
);
ピーターLawrey:

それらを使用してスレッドが死んだ後に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);

これは、例外がスローされることなく、リソースをクローズする方法を持っているのが一般的です。クロニクルは1を持っていますが、非常に多くの他のライブラリを行います。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=184761&siteId=1