ThreadLocal value access across different threads

前端 未结 5 1054
南笙
南笙 2020-12-09 19:29

Given that a ThreadLocal variable holds different values for different threads, is it possible to access the value of one ThreadLocal variable from another thread?

5条回答
  •  隐瞒了意图╮
    2020-12-09 19:59

    Based on the answer of Andrzej Doyle here a full working solution:

    ThreadLocal threadLocal = new ThreadLocal();
    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"
    

    All the previous comments still apply of course - it's not safe!

    But for debugging purposes it might be just what you need - I use it that way.

提交回复
热议问题