Created
June 11, 2019 01:10
-
-
Save chook/9287198237e49863ab131cb63eacf83f to your computer and use it in GitHub Desktop.
thread-name-with-context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collections; | |
import java.util.Deque; | |
import java.util.LinkedList; | |
import java.util.Map; | |
public class ThreadNameWithContext { | |
private static final ThreadLocal<Deque<String>> threadNameStacks = new ThreadLocal<Deque<String>>(); | |
private static final String CONTEXTUAL_THREAD_NAME_FORMAT = "%s [%s]"; | |
public static boolean push(Object key, Object value) { | |
return push(Collections.singletonMap(key, value)); | |
} | |
public static boolean push(Map<?, ?> context) { | |
StringBuilder sb = new StringBuilder(); | |
for (Map.Entry<?, ?> entry : context.entrySet()) { | |
if (sb.length() > 0) { | |
sb.append("; "); | |
} | |
sb.append(entry.getKey()).append(": ").append(entry.getValue()); | |
} | |
return push(sb.toString()); | |
} | |
public static boolean push(String context) { | |
String curThreadName = Thread.currentThread().getName(); | |
String newThreadName = appendContextToThreadName(curThreadName, context); | |
getThreadNameStack().push(curThreadName); | |
Thread.currentThread().setName(newThreadName); | |
return true; | |
} | |
public static boolean pop() { | |
String prevThreadName = getThreadNameStack().poll(); | |
if (prevThreadName == null) { | |
return false; | |
} | |
Thread.currentThread().setName(prevThreadName); | |
return true; | |
} | |
public static void clear() { | |
while (pop()) { | |
} | |
} | |
public static void clearToDepth(int depth) { | |
while (getNameStackDepth() > depth) { | |
if (!pop()) { | |
break; | |
} | |
} | |
} | |
public static int getNameStackDepth() { | |
return getThreadNameStack().size(); | |
} | |
private static String appendContextToThreadName(String threadName, String context) { | |
return String.format(CONTEXTUAL_THREAD_NAME_FORMAT, threadName, context); | |
} | |
private static Deque<String> getThreadNameStack() { | |
Deque<String> threadNameStack = threadNameStacks.get(); | |
if (threadNameStack == null) { | |
threadNameStack = new LinkedList<>(); | |
threadNameStacks.set(threadNameStack); | |
} | |
return threadNameStack; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment