Threadlocal sharing (fine) between threads for user information in session

Source: Internet
Author: User
Tags variable scope

Threadlocal is not difficult to understand, I summarize the simplest understanding is:

threadlocal Like other variables (local, global, Static) is also a variable type, but he is a thread variable, more bluntly he is a variable scope, that is, his scope is the current thread (such as a user's request to calculate a thread), Threadlocal is used to share between one thread. The threadlocal Set (String,object) method is to set the name of the variable, assign it to the variable at the same time, and, of course, give the variable a type.
@SuppressWarnings ("Unchecked")   Public classusersession {Private Static FinalThreadLocal Session_map =NewThreadLocal (); protectedusersession () {} Public StaticObject Get (String attribute) {map map=(MAP) session_map.get (); returnMap.get (attribute); }               Public Static<T> T Get (String attribute, class<t>clazz) {          return(T) get (attribute); }               Public Static voidSet (String attribute, Object value) {map map=(MAP) session_map.get (); if(Map = =NULL) {Map=NewHashMap ();          Session_map.set (MAP);      } map.put (attribute, value); }  }  
The next thing to do is in the request filter:usersession.set ("User", from the session to remove the users information) then we can be in any layer of service or DAO:usersession.get ("user") gets the user information for the current thread Benefits: Avoids the cross-layer parameter transfer, realizes the layer and the layer the loose coupling.

Threadlocal sharing (fine) between threads for user information in session

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.