Simulate sessionfactory. getcurrentsession () of Hibernate with threadlocal Thread Local variable ()
Import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. cfg. configuration; // use threadlocal to simulate the sessionfactory of hibernate. getcurrentsession (); public class hibernateutil {// each thread has a session of sessionprivate static final threadlocal <session> localsession = new threadlocal <session> (); Private Static sessionfactory; static {try {sessionfactory = new configuration (). configure (). buildsessionfactory ();} catch (exception e) {e. printstacktrace () ;}} public static session getcurrentsession () {If (localsession. get () = NULL) localsession. set (sessionfactory. opensession (); Return localsession. get ();}}
So how does threadlocal implement the local variable of the thread ?? Without looking at the JDK source code, the simplest thing is to add a private property XX to each thread, and then getxx () will
Yes, but if we add an attribute to Java. Lang. thread every time we add a "Thread Local variable", that's too much. This is too bad...
The JDK source code contains a map in each thread, and the threadlocalmap threadlocals attribute in Java. Lang. thread is stored in it.
The <key, value> pair (threadlocal key, object Value) is equivalent to the map: Map <threadlocal, Object>,
In the above Code, each thread can put entries such as <localsession, session> into threadlocalmap of the thread...