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