Skip to content

Instantly share code, notes, and snippets.

@andrewfinnell
Created June 29, 2018 13:40
Show Gist options
  • Select an option

  • Save andrewfinnell/e824a0dbb36c964f71fc0f9e96e58fa8 to your computer and use it in GitHub Desktop.

Select an option

Save andrewfinnell/e824a0dbb36c964f71fc0f9e96e58fa8 to your computer and use it in GitHub Desktop.
ThreadLocal Access (Java)
ThreadLocal<String> threadLocal = new ThreadLocal<String>();
threadLocal.set("Test"); // do this in otherThread
Thread otherThread = Thread.currentThread(); // get a reference to the otherThread somehow (this is just for demo)
Field field = Thread.class.getDeclaredField("threadLocals");
field.setAccessible(true);
Object map = field.get(otherThread);
Method method = Class.forName("java.lang.ThreadLocal$ThreadLocalMap").getDeclaredMethod("getEntry", ThreadLocal.class);
method.setAccessible(true);
WeakReference entry = (WeakReference) method.invoke(map, threadLocal);
Field valueField = Class.forName("java.lang.ThreadLocal$ThreadLocalMap$Entry").getDeclaredField("value");
valueField.setAccessible(true);
Object value = valueField.get(entry);
System.out.println("value: " + value); // prints: "value: Test"
public static void injectThreadExitCallback(final Runnable callback) {
final curr = Thread.currentThread();
new Thread() {
@Override
public void run() {
try {
curr.join();
} catch (InterruptedException ex) {
} finally {
callback.run();
}
}
}.start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment