2424
2525package org .jenkinsci .plugins .workflow .support .concurrent ;
2626
27+ import java .lang .*;
28+ import java .util .logging .Logger ;
29+
30+ import jenkins .util .SystemProperties ;
31+
2732/**
2833 * Utility to temporarily append some information to the name of the current thread.
2934 * This is helpful for making thread dumps more readable and informative:
3035 * stack trace elements do not contain any information about object identity.
3136 */
3237public final class WithThreadName implements AutoCloseable {
33-
38+ /** Save original thread name to recover it in {@link #close} call.
39+ * Remains {@code null} if activity of this class is explicitly not
40+ * {@link #enabled} on a particular deployment.
41+ */
3442 private final String original ;
3543
44+ /** Optional toggle via JVM properties to skip work here,
45+ * and forfeit easy debugging, e.g. on systems where
46+ * java.lang.Thread.setNativeName(Native Method) aka
47+ * JVM_SetNativeThreadName() and further platform
48+ * specific implementation takes inexplicably long.
49+ */
50+ private final static boolean enabled = SystemProperties .getBoolean (WithThreadName .class .getName () + ".enabled" , true );
51+
52+ /** Help gauge how much and how often this code gets called */
53+ private static final Logger LOGGER = Logger .getLogger (WithThreadName .class .getName ());
54+
3655 /**
3756 * Sets the current thread’s name.
3857 * @param suffix text to append to the original name
3958 */
4059 public WithThreadName (String suffix ) {
60+ if (!enabled ) {
61+ original = null ;
62+ LOGGER .fine (() -> "SKIP: Neutered WithThreadName(\" " + (suffix == null ? "(null)" : suffix ) + "\" )" );
63+ return ;
64+ }
65+
4166 Thread t = Thread .currentThread ();
4267 original = t .getName ();
4368 t .setName (original + suffix );
@@ -47,6 +72,12 @@ public WithThreadName(String suffix) {
4772 * Restores the original name.
4873 */
4974 @ Override public void close () {
75+ if (!enabled ) {
76+ /* We did not track origin nor suffix here to be fast when skipping, so eh */
77+ LOGGER .fine (() -> "SKIP: Neutered WithThreadName.close()" );
78+ return ;
79+ }
80+
5081 Thread .currentThread ().setName (original );
5182 }
5283
0 commit comments