src/java.base/share/classes/sun/nio/ch/Util.java
changeset 50719 106dc156ce6b
parent 47428 d72d7d55c765
child 57804 9b7b9f16dfd9
--- a/src/java.base/share/classes/sun/nio/ch/Util.java	Fri Jun 22 21:42:00 2018 +0800
+++ b/src/java.base/share/classes/sun/nio/ch/Util.java	Fri Jun 22 17:56:55 2018 +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.TerminatingThreadLocal;
 import jdk.internal.misc.Unsafe;
 import sun.security.action.GetPropertyAction;
-import java.io.IOException;
 
 public class Util {
 
@@ -50,13 +52,18 @@
     private static final long MAX_CACHED_BUFFER_SIZE = getMaxCachedBufferSize();
 
     // Per-thread cache of temporary direct buffers
-    private static ThreadLocal<BufferCache> bufferCache =
-        new ThreadLocal<BufferCache>()
-    {
+    private static ThreadLocal<BufferCache> bufferCache = new TerminatingThreadLocal<>() {
         @Override
         protected BufferCache initialValue() {
             return new BufferCache();
         }
+        @Override
+        protected void threadTerminated(BufferCache cache) { // will never be null
+            while (!cache.isEmpty()) {
+                ByteBuffer bb = cache.removeFirst();
+                free(bb);
+            }
+        }
     };
 
     /**