Created
June 29, 2018 13:40
-
-
Save andrewfinnell/e824a0dbb36c964f71fc0f9e96e58fa8 to your computer and use it in GitHub Desktop.
ThreadLocal Access (Java)
This file contains hidden or 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
| 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