The threadlocal of Java Learning

Source: Internet
Author: User
Tags dateformat

transferred from: http://www.cnblogs.com/doit8791/p/4093808.html#3197185in the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult. Threadlocal, however, solves multiple threads of concurrent access from another angle. Threadlocal provides a separate copy of the variable for each thread , isolating the access violation of multiple threads to the data. because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code. since threadlocal can hold any type of object, the Get () provided by the lower JDK returns an object, which requires casting, but JDK 5.0 solves the problem well by generics. Simplifying the use of threadlocal to some extentTo sum up, for multi-threaded resource sharing problem, the synchronization mechanism adopted the "time-to-space" approach, and threadlocal adopted a "space-time" approach, the former only provides a variable, so that different threads queued access, the latter for each thread has provided a copy of the variable, So they can be accessed at the same time without affecting each other. Spring uses threadlocal to resolve thread safety issueswe know that in general, only stateless beans can be shared in a multithreaded environment, and in spring, most beans can be declared as singleton scopes, is because spring is for some beans (such as Requestcontextholder, Transactionsynchronizationmanager, Localecontextholder, etc.) the non-thread-safe state is handled by threadlocal, making them also a thread-safe state, because stateful beans can be shared across multiple threads. the general Web application divides into the presentation layer, the service layer and the persistence layer three levels, writes the corresponding logic in the different layers, the lower layer through the interface to the upper layer open function calls. in general, all program calls from receiving requests to returning responses belong to one thread. Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency. If your code is in a process where multiple threads are running at the same time, and these threads may run this code at the same time, if the results of each run are the same as the result of a single-threaded run, and the values of the other variables are the same as expected, it is thread-safe. Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization. thread safety issues are caused by global variables and static variables, in general, this global variable is thread-safe if there are only read operations for global variables and static variables in each thread, and if multiple threads are concurrently performing write operations, it is generally necessary to consider thread synchronization, which may affect thread safety. 1) Constants are always thread-safe because only read operations exist. 2) Creating a new instance before each call to the method is thread safe because the shared resource is not accessed. 3) Local variables are thread-safe, because each execution of a method creates a local variable in a separate space, which is not a shared resource, and the local variables include the parameter variables of the method and the in-method variables. A state is a data storage function. Stateful objects (Stateful beans), which are objects with instance variables, can hold data that is non-thread safe. No state is preserved between different method invocations. Stateless is a single operation and cannot hold data. Stateless objects (stateless beans) are objects that do not have an instance variable. Cannot save data, is immutable class, is thread safe. Stateful objects:stateless beans are suitable for invariant patterns, and technology is a singleton mode, which allows you to share instances and improve performance. Stateful beans, which are unsafe in multithreaded environments, are suitable for use with the prototype prototype model. Prototype: A new bean instance is created each time a request is made to the bean. STRUTS2 The default implementation is the prototype mode, which means that each request is reborn as an action instance, so there is no thread safety issue. It is important to note that if the life cycle of the action is managed by spring, scope is to be paired with the prototype scope.

Two, thread safety case:

there is a calendar object reference inside the SimpleDateFormat (SDF) class that is used to store date information related to this SDF, such as Sdf.parse (DATESTR), Sdf.format (date) The method parameters passed in the date-related string, date and so on, are referred to the calendar for storage, which will cause a problem, if your SDF is static, then the multiple thread will share this SDF, Also share this calendar reference, and, observing the Sdf.parse () method, you will find a call like the following:Date Parse () {calendar.clear ();//Clear Calendar...//perform some operations, set calendar date for whatcalendar.gettime ();//Get Calendar Time}The problem here is that if thread A calls Sdf.parse () and does not perform calendar.gettime () after calendar.clear (), thread B calls Sdf.parse (), At this point, thread B also executes the Sdf.clear () method, which causes the calendar data for thread A to be emptied (actually, a, B is emptied at the same time), or when a executes calendar.clear () is suspended, then B begins to call Sdf.parse () and smooth I end so that the date stored in A's calendar becomes the date of the calendar that was later set by BThere is a more important problem behind this question-stateless: one of the benefits of a stateless approach is that it can be safely invoked in a variety of environments . To measure whether a method is stateful, see if it changes something else, such as a global variable, such as an instance field . The Format method changes the Calendar field of the SimpleDateFormat during the run, so it is stateful. This also reminds us to note the next three points when developing and designing the system:1. When you write a common class, make a clear explanation of the consequences of the multi-threaded call case in the comments2. Be aware of thread safety for each shared mutable variable in a threaded environment3. Our classes and methods are designed to be as stateless as possible. three. Workaround1. Create a new instance when needed:Note: When you need to use a new instance of SimpleDateFormat, you can avoid multithreading problems whenever you change the thread security problem object from shared to local private, but it also adds to the burden of creating objects. In general, this is actually less noticeable than the performance impact.  2. Using sync: Synchronizing SimpleDateFormat objects
1  Public classDatesyncutil {2     Private StaticSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");3      Public StaticString formatdate (date date)throwsparseexception{4         synchronized(SDF) {5             returnSdf.format (date);6         }  7     }8      Public StaticDate Parse (String strdate)throwsparseexception{9         synchronized(SDF) {Ten             returnSdf.parse (strdate); One         } A     }  -}
Note: When a thread calls this method when a thread is many, other threads that want to call this method will block, and multithreading concurrency can have a certain effect on performance. 3. Use threadlocal:
1  Public classConcurrentdateutil {2  3     Private StaticThreadlocal<dateformat> ThreadLocal =NewThreadlocal<dateformat>() {4 @Override5         protectedDateFormat InitialValue () {6             return NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");7         }8     };9  Ten      Public StaticDate Parse (String datestr)throwsParseException { One         returnThreadlocal.get (). Parse (DATESTR); A     } -   -      Public StaticString Format (date date) { the         returnthreadlocal.get (). Format (date); -     } - } - or +  Public classThreadlocaldateutil { -     Private Static FinalString date_format = "Yyyy-mm-dd HH:mm:ss"; +     Private StaticThreadlocal<dateformat> ThreadLocal =NewThreadlocal<dateformat>();  A   at      Public StaticDateFormat GetDateFormat () -     {   -DateFormat DF =Threadlocal.get ();  -         if(df==NULL){   -DF =NewSimpleDateFormat (Date_format);  - Threadlocal.set (DF);  in         }   -         returnDF;  to     }   +   -      Public StaticString formatdate (date date)throwsParseException { the         returnGetDateFormat (). Format (date); *     } $  Panax Notoginseng      Public StaticDate Parse (String strdate)throwsParseException { -         returnGetDateFormat (). Parse (strdate); the     }    +}
Description: Using threadlocal, the shared variable is also changed to exclusive, the thread exclusive can be compared to the method exclusive in the concurrency environment can reduce the cost of many objects created. This approach is generally recommended if performance requirements are high. 4. Discard the JDK and use the time formatting classes from other class libraries:1. Using Apache Commons Fastdateformat, claiming to be both fast and thread-safe simpledateformat, unfortunately it can only format the date, cannot parse the date string. 2. Use the Joda-time class library to handle time-related issuesTo do a simple stress test, the method of the slowest, method three the fastest, but even the slowest method a performance is not bad, the general system method one and the method two can be satisfied, so that in this point is difficult to become the bottleneck of your system. From a simple point of view, it is recommended to use method one or method two, if necessary, the pursuit of a bit of performance improvement, you can consider using method three, with threadlocal cache. Joda-time class Library is perfect for time processing, it is recommended.

The threadlocal of Java Learning

Related Article

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.