How do I close a thread local autocloseable used in parallel stream?

hey_you :

I have a ThreadLocal variable. I would like to use it like this:

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?*/
    })
);
Peter Lawrey :

ThreadLocal are closed after the thread using them dies. If you want control over this you need to use a map instead.

// 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);

It's common to have a method which closes resources without throwing an exception. Chronicle has one but so do many other libraries.

public static void closeQuietly(Closeable c) {
    if (c != null) {
       try {
           c.close();
       } catch (IOException ioe) {
           // ignore or trace log it
       }
    }
}

Most likely you have a method do this in your project already https://www.google.co.uk/search?q=public+static+void+closequietly+Closeable

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74128&siteId=1