3636/**
3737 * A byte buffer pool that supports reference counted pools.
3838 *
39- * TODO: move this somewhere more appropriate
40- *
4139 * @author Stuart Douglas
4240 */
41+ // TODO: move this somewhere more appropriate
4342public class DefaultByteBufferPool implements ByteBufferPool {
4443
4544 private final ThreadLocalCache threadLocalCache = new ThreadLocalCache ();
@@ -169,7 +168,7 @@ public ByteBufferPool getArrayBackedPool() {
169168 private void cleanupThreadLocalData () {
170169 // Called under lock, and only when at least quarter of the capacity has been collected.
171170
172- int size = threadLocalDataList .size ();
171+ final int size = threadLocalDataList .size ();
173172
174173 if (reclaimedThreadLocals > (size / 4 )) {
175174 int j = 0 ;
@@ -192,7 +191,7 @@ private void freeInternal(ByteBuffer buffer) {
192191 DirectByteBufferDeallocator .free (buffer );
193192 return ; //GC will take care of it
194193 }
195- ThreadLocalData local = threadLocalCache .get ();
194+ final ThreadLocalData local = threadLocalCache .get ();
196195 if (local != null ) {
197196 if (local .allocationDepth > 0 ) {
198197 local .allocationDepth --;
@@ -227,12 +226,12 @@ public void close() {
227226
228227 synchronized (threadLocalDataList ) {
229228 for (WeakReference <ThreadLocalData > ref : threadLocalDataList ) {
230- ThreadLocalData local = ref .get ();
229+ final ThreadLocalData local = ref .get ();
230+ ref .clear ();
231231 if (local != null ) {
232232 local .buffers .clear ();
233+ threadLocalCache .remove (local );
233234 }
234- ref .clear ();
235- threadLocalCache .remove (local );
236235 }
237236 threadLocalDataList .clear ();
238237 }
@@ -299,7 +298,7 @@ public String toString() {
299298 }
300299
301300 private class ThreadLocalData {
302- ArrayDeque <ByteBuffer > buffers = new ArrayDeque <>(threadLocalCacheSize );
301+ final ArrayDeque <ByteBuffer > buffers = new ArrayDeque <>(threadLocalCacheSize );
303302 int allocationDepth = 0 ;
304303
305304 @ Override
@@ -344,7 +343,7 @@ protected void finalize() throws Throwable {
344343 // class can be called by a different thread than the one that initialized the data.
345344 private static class ThreadLocalCache {
346345
347- Map <Thread , ThreadLocalData > localsByThread = Collections .synchronizedMap (new WeakHashMap <>());
346+ final Map <Thread , ThreadLocalData > localsByThread = Collections .synchronizedMap (new WeakHashMap <>());
348347
349348 ThreadLocalData get () {
350349 return localsByThread .get (Thread .currentThread ());
0 commit comments