Use threadlocal to simulate hibernate getcurrentsession ()

Source: Internet
Author: User

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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.