Java is required for work, and there are many things to learn. I have to say goodbye to. Net temporarily.
When I was looking at spring, I suddenly thought of threadstaticattribute in. Net (allowing static variables to be different in different threads ).
In many cases, the content in each execution thread is fixed, such as the servlet currentuser/httpcontext/session in the Web environment. in many cases, these variables are transferred to the back-layer class, resulting in complicated design.
A good design method in. NET is static: thread. currentprincipal/httpcontext. Current ....
Is there a similar mechanism in Java? The answer is threadlocal.
Api doc: http://java.sun.com/j2se/1.4.2/docs/api/index.html
Brian Goetz'sArticle: Http://www-900.ibm.com/developerWorks/cn/java/j-threads/index3.shtml
Brian Goetz pointed out in the article that threadlocal performance in jdk1.4 can be avoided.
The usage is more complex than. net, and the API examples are quite weird. Here is an example I wrote myself: Public Class Hello implements runnable {
Static Class Counter {
Int C = 0 ;
Public Void Count () {
System.Out. Println (thread. currentthread (). hashcode ()+ ":"+C++);
}
}
Private Static Threadlocal counter = New Threadlocal () {
ProtectedObject initialvalue (){Return NewCounter ();}
} ;
Public Static Counter () {Return(Counter) counter.Get();}
Public Static Void Main (string [] ARGs) throws exception {< br> Hello H = New Hello ();
H. run ();
New thread ( New Hello ()). start ();
thread. sleep ( 1000l );
H. run ();
counter (). count ();
}
Public Void Run () {
Counter (). Count ();
Counter (). Count ();
Counter (). Count ();
}
}
Result: 25358555 : 0
25358555 : 1
25358555 : 2
26399554 : 0
26399554 : 1
26399554 : 2
25358555 : 3
25358555 : 4
25358555 : 5
25358555 : 6
Threadlocal works well. Note that threadlocal is similar to an access media. The value returned by get () is stored in the current thread.
It is worth noting that the inheritablethreadlocal class can transmit threadlocal data to the Child thread.
In addition, Servlet threads may be reused. Note that each servlet is reinitialized at the beginning.