--- old/src/java.base/share/classes/sun/nio/fs/NativeBuffers.java 2018-05-18 10:13:27.313831818 +0200 +++ new/src/java.base/share/classes/sun/nio/fs/NativeBuffers.java 2018-05-18 10:13:27.219833416 +0200 @@ -25,6 +25,7 @@ package sun.nio.fs; +import jdk.internal.misc.JdkThreadLocal; import jdk.internal.misc.Unsafe; /** @@ -37,8 +38,22 @@ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final int TEMP_BUF_POOL_SIZE = 3; - private static ThreadLocal threadLocal = - new ThreadLocal(); + private static ThreadLocal threadLocal = new JdkThreadLocal<>() { + @Override + protected void threadTerminated() { + NativeBuffer[] buffers = get(); + // threadLocal may be initialized but with initialValue of null + if (buffers != null) { + for (int i = 0; i < TEMP_BUF_POOL_SIZE; i++) { + NativeBuffer buffer = buffers[i]; + if (buffer != null) { + buffer.free(); + buffers[i] = null; + } + } + } + } + }; /** * Allocates a native buffer, of at least the given size, from the heap.