Java, bind something to a thread

I was just wondering how some libraries can detect in which thread they are running, and "bind" something to it ... for example, Mapped Diagnostic Context (MDC) log4j or Context.enter () from Mozilla Rhino. How can I do this, just in case, I will come across a case when I need it .; -)

Have a nice day!

+3
source share
1 answer

You can get thread information using ThreadLocal variables . I don't know anything about the details of Rhino or log4j, but I think they do that.

An example from Javadoc that assigns a different serial number to each serial number.

 public class SerialNum {
     // The next serial number to be assigned
     private static int nextSerialNum = 0;

     private static ThreadLocal serialNum = new ThreadLocal() {
         protected synchronized Object initialValue() {
             return new Integer(nextSerialNum++);
         }
     };

     public static int get() {
         return ((Integer) (serialNum.get())).intValue();
     }
 }
+8
source

Source: https://habr.com/ru/post/1713150/


All Articles