--- old/src/java.base/share/classes/sun/nio/ch/Util.java 2018-05-18 10:13:27.012836936 +0200 +++ new/src/java.base/share/classes/sun/nio/ch/Util.java 2018-05-18 10:13:26.924838433 +0200 @@ -26,6 +26,7 @@ package sun.nio.ch; import java.io.FileDescriptor; +import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; @@ -35,9 +36,10 @@ import java.util.Collection; import java.util.Iterator; import java.util.Set; + +import jdk.internal.misc.JdkThreadLocal; import jdk.internal.misc.Unsafe; import sun.security.action.GetPropertyAction; -import java.io.IOException; public class Util { @@ -50,13 +52,19 @@ private static final long MAX_CACHED_BUFFER_SIZE = getMaxCachedBufferSize(); // Per-thread cache of temporary direct buffers - private static ThreadLocal bufferCache = - new ThreadLocal() - { + private static ThreadLocal bufferCache = new JdkThreadLocal<>() { @Override - protected BufferCache initialValue() { + protected BufferCache computeInitialValue() { return new BufferCache(); } + @Override + protected void threadTerminated() { + BufferCache cache = get(); // will never be null + while (!cache.isEmpty()) { + ByteBuffer bb = cache.removeFirst(); + free(bb); + } + } }; /**