View Javadoc
1   /*
2    * Copyright 2013 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.util;
18  
19  import io.netty.util.internal.EmptyArrays;
20  import io.netty.util.internal.ObjectUtil;
21  import io.netty.util.internal.PlatformDependent;
22  import io.netty.util.internal.SystemPropertyUtil;
23  import io.netty.util.internal.logging.InternalLogger;
24  import io.netty.util.internal.logging.InternalLoggerFactory;
25  
26  import java.lang.ref.ReferenceQueue;
27  import java.lang.ref.WeakReference;
28  import java.lang.reflect.Method;
29  import java.util.Arrays;
30  import java.util.Collections;
31  import java.util.HashSet;
32  import java.util.Set;
33  import java.util.concurrent.ConcurrentHashMap;
34  import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
35  import java.util.concurrent.atomic.AtomicReference;
36  import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
37  
38  import static io.netty.util.internal.StringUtil.EMPTY_STRING;
39  import static io.netty.util.internal.StringUtil.NEWLINE;
40  import static io.netty.util.internal.StringUtil.simpleClassName;
41  
42  public class ResourceLeakDetector<T> {
43  
44      private static final String PROP_LEVEL_OLD = "io.netty.leakDetectionLevel";
45      private static final String PROP_LEVEL = "io.netty.leakDetection.level";
46      private static final Level DEFAULT_LEVEL = Level.SIMPLE;
47  
48      private static final String PROP_TARGET_RECORDS = "io.netty.leakDetection.targetRecords";
49      private static final int DEFAULT_TARGET_RECORDS = 4;
50  
51      private static final String PROP_SAMPLING_INTERVAL = "io.netty.leakDetection.samplingInterval";
52      // There is a minor performance benefit in TLR if this is a power of 2.
53      private static final int DEFAULT_SAMPLING_INTERVAL = 128;
54  
55      private static final int TARGET_RECORDS;
56      static final int SAMPLING_INTERVAL;
57  
58      /**
59       * Represents the level of resource leak detection.
60       */
61      public enum Level {
62          /**
63           * Disables resource leak detection.
64           */
65          DISABLED,
66          /**
67           * Enables simplistic sampling resource leak detection which reports there is a leak or not,
68           * at the cost of small overhead (default).
69           */
70          SIMPLE,
71          /**
72           * Enables advanced sampling resource leak detection which reports where the leaked object was accessed
73           * recently at the cost of high overhead.
74           */
75          ADVANCED,
76          /**
77           * Enables paranoid resource leak detection which reports where the leaked object was accessed recently,
78           * at the cost of the highest possible overhead (for testing purposes only).
79           */
80          PARANOID;
81  
82          /**
83           * Returns level based on string value. Accepts also string that represents ordinal number of enum.
84           *
85           * @param levelStr - level string : DISABLED, SIMPLE, ADVANCED, PARANOID. Ignores case.
86           * @return corresponding level or SIMPLE level in case of no match.
87           */
88          static Level parseLevel(String levelStr) {
89              String trimmedLevelStr = levelStr.trim();
90              for (Level l : values()) {
91                  if (trimmedLevelStr.equalsIgnoreCase(l.name()) || trimmedLevelStr.equals(String.valueOf(l.ordinal()))) {
92                      return l;
93                  }
94              }
95              return DEFAULT_LEVEL;
96          }
97      }
98  
99      private static Level level;
100 
101     private static final InternalLogger logger = InternalLoggerFactory.getInstance(ResourceLeakDetector.class);
102 
103     static {
104         final boolean disabled;
105         if (SystemPropertyUtil.get("io.netty.noResourceLeakDetection") != null) {
106             disabled = SystemPropertyUtil.getBoolean("io.netty.noResourceLeakDetection", false);
107             logger.debug("-Dio.netty.noResourceLeakDetection: {}", disabled);
108             logger.warn(
109                     "-Dio.netty.noResourceLeakDetection is deprecated. Use '-D{}={}' instead.",
110                     PROP_LEVEL, Level.DISABLED.name().toLowerCase());
111         } else {
112             disabled = false;
113         }
114 
115         Level defaultLevel = disabled? Level.DISABLED : DEFAULT_LEVEL;
116 
117         // First read old property name
118         String levelStr = SystemPropertyUtil.get(PROP_LEVEL_OLD, defaultLevel.name());
119 
120         // If new property name is present, use it
121         levelStr = SystemPropertyUtil.get(PROP_LEVEL, levelStr);
122         Level level = Level.parseLevel(levelStr);
123 
124         TARGET_RECORDS = SystemPropertyUtil.getInt(PROP_TARGET_RECORDS, DEFAULT_TARGET_RECORDS);
125         SAMPLING_INTERVAL = SystemPropertyUtil.getInt(PROP_SAMPLING_INTERVAL, DEFAULT_SAMPLING_INTERVAL);
126 
127         ResourceLeakDetector.level = level;
128         if (logger.isDebugEnabled()) {
129             logger.debug("-D{}: {}", PROP_LEVEL, level.name().toLowerCase());
130             logger.debug("-D{}: {}", PROP_TARGET_RECORDS, TARGET_RECORDS);
131         }
132     }
133 
134     /**
135      * @deprecated Use {@link #setLevel(Level)} instead.
136      */
137     @Deprecated
138     public static void setEnabled(boolean enabled) {
139         setLevel(enabled? Level.SIMPLE : Level.DISABLED);
140     }
141 
142     /**
143      * Returns {@code true} if resource leak detection is enabled.
144      */
145     public static boolean isEnabled() {
146         return getLevel().ordinal() > Level.DISABLED.ordinal();
147     }
148 
149     /**
150      * Sets the resource leak detection level.
151      */
152     public static void setLevel(Level level) {
153         ResourceLeakDetector.level = ObjectUtil.checkNotNull(level, "level");
154     }
155 
156     /**
157      * Returns the current resource leak detection level.
158      */
159     public static Level getLevel() {
160         return level;
161     }
162 
163     /** the collection of active resources */
164     private final Set<DefaultResourceLeak<?>> allLeaks =
165             Collections.newSetFromMap(new ConcurrentHashMap<DefaultResourceLeak<?>, Boolean>());
166 
167     private final ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>();
168     private final Set<String> reportedLeaks =
169             Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
170 
171     private final String resourceType;
172     private final int samplingInterval;
173 
174     /**
175      * Will be notified once a leak is detected.
176      */
177     private volatile LeakListener leakListener;
178 
179     /**
180      * @deprecated use {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class, int, long)}.
181      */
182     @Deprecated
183     public ResourceLeakDetector(Class<?> resourceType) {
184         this(simpleClassName(resourceType));
185     }
186 
187     /**
188      * @deprecated use {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class, int, long)}.
189      */
190     @Deprecated
191     public ResourceLeakDetector(String resourceType) {
192         this(resourceType, DEFAULT_SAMPLING_INTERVAL, Long.MAX_VALUE);
193     }
194 
195     /**
196      * @deprecated Use {@link ResourceLeakDetector#ResourceLeakDetector(Class, int)}.
197      * <p>
198      * This should not be used directly by users of {@link ResourceLeakDetector}.
199      * Please use {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class)}
200      * or {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class, int, long)}
201      *
202      * @param maxActive This is deprecated and will be ignored.
203      */
204     @Deprecated
205     public ResourceLeakDetector(Class<?> resourceType, int samplingInterval, long maxActive) {
206         this(resourceType, samplingInterval);
207     }
208 
209     /**
210      * This should not be used directly by users of {@link ResourceLeakDetector}.
211      * Please use {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class)}
212      * or {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class, int, long)}
213      */
214     @SuppressWarnings("deprecation")
215     public ResourceLeakDetector(Class<?> resourceType, int samplingInterval) {
216         this(simpleClassName(resourceType), samplingInterval, Long.MAX_VALUE);
217     }
218 
219     /**
220      * @deprecated use {@link ResourceLeakDetectorFactory#newResourceLeakDetector(Class, int, long)}.
221      * <p>
222      * @param maxActive This is deprecated and will be ignored.
223      */
224     @Deprecated
225     public ResourceLeakDetector(String resourceType, int samplingInterval, long maxActive) {
226         this.resourceType = ObjectUtil.checkNotNull(resourceType, "resourceType");
227         this.samplingInterval = samplingInterval;
228     }
229 
230     /**
231      * Creates a new {@link ResourceLeak} which is expected to be closed via {@link ResourceLeak#close()} when the
232      * related resource is deallocated.
233      *
234      * @return the {@link ResourceLeak} or {@code null}
235      * @deprecated use {@link #track(Object)}
236      */
237     @Deprecated
238     public final ResourceLeak open(T obj) {
239         return track0(obj, false);
240     }
241 
242     /**
243      * Creates a new {@link ResourceLeakTracker} which is expected to be closed via
244      * {@link ResourceLeakTracker#close(Object)} when the related resource is deallocated.
245      *
246      * @return the {@link ResourceLeakTracker} or {@code null}
247      */
248     @SuppressWarnings("unchecked")
249     public final ResourceLeakTracker<T> track(T obj) {
250         return track0(obj, false);
251     }
252 
253     /**
254      * Creates a new {@link ResourceLeakTracker} which is expected to be closed via
255      * {@link ResourceLeakTracker#close(Object)} when the related resource is deallocated.
256      *
257      * Unlike {@link #track(Object)}, this method always returns a tracker, regardless
258      * of the detection settings.
259      *
260      * @return the {@link ResourceLeakTracker}
261      */
262     @SuppressWarnings("unchecked")
263     public ResourceLeakTracker<T> trackForcibly(T obj) {
264         return track0(obj, true);
265     }
266 
267     @SuppressWarnings("unchecked")
268     private DefaultResourceLeak track0(T obj, boolean force) {
269         Level level = ResourceLeakDetector.level;
270         if (force ||
271                 level == Level.PARANOID ||
272                 (level != Level.DISABLED && PlatformDependent.threadLocalRandom().nextInt(samplingInterval) == 0)) {
273             reportLeak();
274             return new DefaultResourceLeak(obj, refQueue, allLeaks, getInitialHint(resourceType));
275         }
276         return null;
277     }
278 
279     private void clearRefQueue() {
280         for (;;) {
281             DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll();
282             if (ref == null) {
283                 break;
284             }
285             ref.dispose();
286         }
287     }
288 
289     /**
290      * When the return value is {@code true}, {@link #reportTracedLeak} and {@link #reportUntracedLeak}
291      * will be called once a leak is detected, otherwise not.
292      *
293      * @return {@code true} to enable leak reporting.
294      */
295     protected boolean needReport() {
296         return logger.isErrorEnabled();
297     }
298 
299     private void reportLeak() {
300         boolean report = needReport();
301         if (!report && leakListener == null) {
302             clearRefQueue();
303             return;
304         }
305 
306         // Detect and report previous leaks.
307         for (;;) {
308             DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll();
309             if (ref == null) {
310                 break;
311             }
312 
313             if (!ref.dispose()) {
314                 continue;
315             }
316 
317             String records = ref.getReportAndClearRecords();
318             if (report && reportedLeaks.add(records)) {
319                 if (records.isEmpty()) {
320                     reportUntracedLeak(resourceType);
321                 } else {
322                     reportTracedLeak(resourceType, records);
323                 }
324             }
325 
326             LeakListener listener = leakListener;
327             if (listener != null) {
328                 listener.onLeak(resourceType, records);
329             }
330         }
331     }
332 
333     /**
334      * This method is called when a traced leak is detected. It can be overridden for tracking how many times leaks
335      * have been detected.
336      */
337     protected void reportTracedLeak(String resourceType, String records) {
338         logger.error(
339                 "LEAK: {}.release() was not called before it's garbage-collected. " +
340                 "See https://netty.io/wiki/reference-counted-objects.html for more information.{}",
341                 resourceType, records);
342     }
343 
344     /**
345      * This method is called when an untraced leak is detected. It can be overridden for tracking how many times leaks
346      * have been detected.
347      */
348     protected void reportUntracedLeak(String resourceType) {
349         logger.error("LEAK: {}.release() was not called before it's garbage-collected. " +
350                 "Enable advanced leak reporting to find out where the leak occurred. " +
351                 "To enable advanced leak reporting, " +
352                 "specify the JVM option '-D{}={}' or call {}.setLevel() " +
353                 "See https://netty.io/wiki/reference-counted-objects.html for more information.",
354                 resourceType, PROP_LEVEL, Level.ADVANCED.name().toLowerCase(), simpleClassName(this));
355     }
356 
357     /**
358      * @deprecated This method will no longer be invoked by {@link ResourceLeakDetector}.
359      */
360     @Deprecated
361     protected void reportInstancesLeak(String resourceType) {
362     }
363 
364     /**
365      * Create a hint object to be attached to an object tracked by this record. Similar to the additional information
366      * supplied to {@link ResourceLeakTracker#record(Object)}, will be printed alongside the stack trace of the
367      * creation of the resource.
368      */
369     protected Object getInitialHint(String resourceType) {
370         return null;
371     }
372 
373     /**
374      * Set leak listener. Previous listener will be replaced.
375      */
376     public void setLeakListener(LeakListener leakListener) {
377         this.leakListener = leakListener;
378     }
379 
380     public interface LeakListener {
381 
382         /**
383          * Will be called for every detected leak, including leaks with reports deduplicated in the log.
384          */
385         void onLeak(String resourceType, String records);
386     }
387 
388     @SuppressWarnings("deprecation")
389     private static final class DefaultResourceLeak<T>
390             extends WeakReference<Object> implements ResourceLeakTracker<T>, ResourceLeak {
391 
392         @SuppressWarnings("unchecked") // generics and updaters do not mix.
393         private static final AtomicReferenceFieldUpdater<DefaultResourceLeak<?>, TraceRecord> headUpdater =
394                 (AtomicReferenceFieldUpdater)
395                         AtomicReferenceFieldUpdater.newUpdater(DefaultResourceLeak.class, TraceRecord.class, "head");
396 
397         @SuppressWarnings("unchecked") // generics and updaters do not mix.
398         private static final AtomicIntegerFieldUpdater<DefaultResourceLeak<?>> droppedRecordsUpdater =
399                 (AtomicIntegerFieldUpdater)
400                         AtomicIntegerFieldUpdater.newUpdater(DefaultResourceLeak.class, "droppedRecords");
401 
402         @SuppressWarnings("unused")
403         private volatile TraceRecord head;
404         @SuppressWarnings("unused")
405         private volatile int droppedRecords;
406 
407         private final Set<DefaultResourceLeak<?>> allLeaks;
408         private final int trackedHash;
409 
410         DefaultResourceLeak(
411                 Object referent,
412                 ReferenceQueue<Object> refQueue,
413                 Set<DefaultResourceLeak<?>> allLeaks,
414                 Object initialHint) {
415             super(referent, refQueue);
416 
417             assert referent != null;
418 
419             this.allLeaks = allLeaks;
420 
421             // Store the hash of the tracked object to later assert it in the close(...) method.
422             // It's important that we not store a reference to the referent as this would disallow it from
423             // be collected via the WeakReference.
424             trackedHash = System.identityHashCode(referent);
425             allLeaks.add(this);
426             // Create a new Record so we always have the creation stacktrace included.
427             headUpdater.set(this, initialHint == null ?
428                     new TraceRecord(TraceRecord.BOTTOM) : new TraceRecord(TraceRecord.BOTTOM, initialHint));
429         }
430 
431         @Override
432         public void record() {
433             record0(null);
434         }
435 
436         @Override
437         public void record(Object hint) {
438             record0(hint);
439         }
440 
441         /**
442          * This method works by exponentially backing off as more records are present in the stack. Each record has a
443          * 1 / 2^n chance of dropping the top most record and replacing it with itself. This has a number of convenient
444          * properties:
445          *
446          * <ol>
447          * <li>  The current record is always recorded. This is due to the compare and swap dropping the top most
448          *       record, rather than the to-be-pushed record.
449          * <li>  The very last access will always be recorded. This comes as a property of 1.
450          * <li>  It is possible to retain more records than the target, based upon the probability distribution.
451          * <li>  It is easy to keep a precise record of the number of elements in the stack, since each element has to
452          *     know how tall the stack is.
453          * </ol>
454          *
455          * In this particular implementation, there are also some advantages. A thread local random is used to decide
456          * if something should be recorded. This means that if there is a deterministic access pattern, it is now
457          * possible to see what other accesses occur, rather than always dropping them. Second, after
458          * {@link #TARGET_RECORDS} accesses, backoff occurs. This matches typical access patterns,
459          * where there are either a high number of accesses (i.e. a cached buffer), or low (an ephemeral buffer), but
460          * not many in between.
461          *
462          * The use of atomics avoids serializing a high number of accesses, when most of the records will be thrown
463          * away. High contention only happens when there are very few existing records, which is only likely when the
464          * object isn't shared! If this is a problem, the loop can be aborted and the record dropped, because another
465          * thread won the race.
466          */
467         private void record0(Object hint) {
468             // Check TARGET_RECORDS > 0 here to avoid similar check before remove from and add to lastRecords
469             if (TARGET_RECORDS > 0) {
470                 TraceRecord oldHead;
471                 TraceRecord prevHead;
472                 TraceRecord newHead;
473                 boolean dropped;
474                 do {
475                     if ((prevHead = oldHead = headUpdater.get(this)) == null) {
476                         // already closed.
477                         return;
478                     }
479                     final int numElements = oldHead.pos + 1;
480                     if (numElements >= TARGET_RECORDS) {
481                         final int backOffFactor = Math.min(numElements - TARGET_RECORDS, 30);
482                         if (dropped = PlatformDependent.threadLocalRandom().nextInt(1 << backOffFactor) != 0) {
483                             prevHead = oldHead.next;
484                         }
485                     } else {
486                         dropped = false;
487                     }
488                     newHead = hint != null ? new TraceRecord(prevHead, hint) : new TraceRecord(prevHead);
489                 } while (!headUpdater.compareAndSet(this, oldHead, newHead));
490                 if (dropped) {
491                     droppedRecordsUpdater.incrementAndGet(this);
492                 }
493             }
494         }
495 
496         boolean dispose() {
497             clear();
498             return allLeaks.remove(this);
499         }
500 
501         @Override
502         public boolean close() {
503             if (allLeaks.remove(this)) {
504                 // Call clear so the reference is not even enqueued.
505                 clear();
506                 headUpdater.set(this, null);
507                 return true;
508             }
509             return false;
510         }
511 
512         @Override
513         public boolean close(T trackedObject) {
514             // Ensure that the object that was tracked is the same as the one that was passed to close(...).
515             assert trackedHash == System.identityHashCode(trackedObject);
516 
517             try {
518                 return close();
519             } finally {
520                 // This method will do `synchronized(trackedObject)` and we should be sure this will not cause deadlock.
521                 // It should not, because somewhere up the callstack should be a (successful) `trackedObject.release`,
522                 // therefore it is unreasonable that anyone else, anywhere, is holding a lock on the trackedObject.
523                 // (Unreasonable but possible, unfortunately.)
524                 reachabilityFence0(trackedObject);
525             }
526         }
527 
528          /**
529          * Ensures that the object referenced by the given reference remains
530          * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
531          * regardless of any prior actions of the program that might otherwise cause
532          * the object to become unreachable; thus, the referenced object is not
533          * reclaimable by garbage collection at least until after the invocation of
534          * this method.
535          *
536          * <p> Recent versions of the JDK have a nasty habit of prematurely deciding objects are unreachable.
537          * see: https://stackoverflow.com/questions/26642153/finalize-called-on-strongly-reachable-object-in-java-8
538          * The Java 9 method Reference.reachabilityFence offers a solution to this problem.
539          *
540          * <p> This method is always implemented as a synchronization on {@code ref}, not as
541          * {@code Reference.reachabilityFence} for consistency across platforms and to allow building on JDK 6-8.
542          * <b>It is the caller's responsibility to ensure that this synchronization will not cause deadlock.</b>
543          *
544          * @param ref the reference. If {@code null}, this method has no effect.
545          * @see java.lang.ref.Reference#reachabilityFence
546          */
547         private static void reachabilityFence0(Object ref) {
548             if (ref != null) {
549                 synchronized (ref) {
550                     // Empty synchronized is ok: https://stackoverflow.com/a/31933260/1151521
551                 }
552             }
553         }
554 
555         @Override
556         public String toString() {
557             TraceRecord oldHead = headUpdater.get(this);
558             return generateReport(oldHead);
559         }
560 
561         String getReportAndClearRecords() {
562             TraceRecord oldHead = headUpdater.getAndSet(this, null);
563             return generateReport(oldHead);
564         }
565 
566         private String generateReport(TraceRecord oldHead) {
567             if (oldHead == null) {
568                 // Already closed
569                 return EMPTY_STRING;
570             }
571 
572             final int dropped = droppedRecordsUpdater.get(this);
573             int duped = 0;
574 
575             int present = oldHead.pos + 1;
576             // Guess about 2 kilobytes per stack trace
577             StringBuilder buf = new StringBuilder(present * 2048).append(NEWLINE);
578             buf.append("Recent access records: ").append(NEWLINE);
579 
580             int i = 1;
581             Set<String> seen = new HashSet<String>(present);
582             for (; oldHead != TraceRecord.BOTTOM; oldHead = oldHead.next) {
583                 String s = oldHead.toString();
584                 if (seen.add(s)) {
585                     if (oldHead.next == TraceRecord.BOTTOM) {
586                         buf.append("Created at:").append(NEWLINE).append(s);
587                     } else {
588                         buf.append('#').append(i++).append(':').append(NEWLINE).append(s);
589                     }
590                 } else {
591                     duped++;
592                 }
593             }
594 
595             if (duped > 0) {
596                 buf.append(": ")
597                         .append(duped)
598                         .append(" leak records were discarded because they were duplicates")
599                         .append(NEWLINE);
600             }
601 
602             if (dropped > 0) {
603                 buf.append(": ")
604                    .append(dropped)
605                    .append(" leak records were discarded because the leak record count is targeted to ")
606                    .append(TARGET_RECORDS)
607                    .append(". Use system property ")
608                    .append(PROP_TARGET_RECORDS)
609                    .append(" to increase the limit.")
610                    .append(NEWLINE);
611             }
612 
613             buf.setLength(buf.length() - NEWLINE.length());
614             return buf.toString();
615         }
616     }
617 
618     private static final AtomicReference<String[]> excludedMethods =
619             new AtomicReference<String[]>(EmptyArrays.EMPTY_STRINGS);
620 
621     public static void addExclusions(Class clz, String ... methodNames) {
622         Set<String> nameSet = new HashSet<String>(Arrays.asList(methodNames));
623         // Use loop rather than lookup. This avoids knowing the parameters, and doesn't have to handle
624         // NoSuchMethodException.
625         for (Method method : clz.getDeclaredMethods()) {
626             if (nameSet.remove(method.getName()) && nameSet.isEmpty()) {
627                 break;
628             }
629         }
630         if (!nameSet.isEmpty()) {
631             throw new IllegalArgumentException("Can't find '" + nameSet + "' in " + clz.getName());
632         }
633         String[] oldMethods;
634         String[] newMethods;
635         do {
636             oldMethods = excludedMethods.get();
637             newMethods = Arrays.copyOf(oldMethods, oldMethods.length + 2 * methodNames.length);
638             for (int i = 0; i < methodNames.length; i++) {
639                 newMethods[oldMethods.length + i * 2] = clz.getName();
640                 newMethods[oldMethods.length + i * 2 + 1] = methodNames[i];
641             }
642         } while (!excludedMethods.compareAndSet(oldMethods, newMethods));
643     }
644 
645     private static class TraceRecord extends Throwable {
646         private static final long serialVersionUID = 6065153674892850720L;
647 
648         private static final TraceRecord BOTTOM = new TraceRecord() {
649             private static final long serialVersionUID = 7396077602074694571L;
650 
651             // Override fillInStackTrace() so we not populate the backtrace via a native call and so leak the
652             // Classloader.
653             // See https://github.com/netty/netty/pull/10691
654             @Override
655             public Throwable fillInStackTrace() {
656                 return this;
657             }
658         };
659 
660         private final String hintString;
661         private final TraceRecord next;
662         private final int pos;
663 
664         TraceRecord(TraceRecord next, Object hint) {
665             // This needs to be generated even if toString() is never called as it may change later on.
666             hintString = hint instanceof ResourceLeakHint ? ((ResourceLeakHint) hint).toHintString() : hint.toString();
667             this.next = next;
668             this.pos = next.pos + 1;
669         }
670 
671         TraceRecord(TraceRecord next) {
672            hintString = null;
673            this.next = next;
674            this.pos = next.pos + 1;
675         }
676 
677         // Used to terminate the stack
678         private TraceRecord() {
679             hintString = null;
680             next = null;
681             pos = -1;
682         }
683 
684         @Override
685         public String toString() {
686             StringBuilder buf = new StringBuilder(2048);
687             if (hintString != null) {
688                 buf.append("\tHint: ").append(hintString).append(NEWLINE);
689             }
690 
691             // Append the stack trace.
692             StackTraceElement[] array = getStackTrace();
693             // Skip the first three elements.
694             out: for (int i = 3; i < array.length; i++) {
695                 StackTraceElement element = array[i];
696                 // Strip the noisy stack trace elements.
697                 String[] exclusions = excludedMethods.get();
698                 for (int k = 0; k < exclusions.length; k += 2) {
699                     // Suppress a warning about out of bounds access
700                     // since the length of excludedMethods is always even, see addExclusions()
701                     if (exclusions[k].equals(element.getClassName())
702                             && exclusions[k + 1].equals(element.getMethodName())) {
703                         continue out;
704                     }
705                 }
706 
707                 buf.append('\t');
708                 buf.append(element.toString());
709                 buf.append(NEWLINE);
710             }
711             return buf.toString();
712         }
713     }
714 }