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