"Go" Summary of 3 keywords (volatile, ThreadLocal, synchronized) easily confused in Java multithreaded programming

Source: Internet
Author: User
Tags volatile

Overview

Recently in the read "Thinking in Java", see the multi-threaded chapters feel that there are some concepts easier to confuse the need to summarize, although not new things, but still very important, very basic, in the development or reading the source code will often encounter, here is a simple summary.

1.volatile

Volatile is primarily used to synchronize variables in multiple threads.
In general, in order to improve performance, each thread at run time will save the variables in the main memory as a copy of the variable in its own memory, but it is easy to show that the replica variables saved in multiple threads are inconsistent, or inconsistent with the variable values in the main memory.
When a variable is modified by volatile, the variable cannot be cached in the thread's memory, it tells the compiler not to perform any optimizations that remove read and write operations, in other words, it does not allow a copy of the variable that differs from the "main" memory area, so when the variable changes, All threads that call the variable will get the same value, which ensures that the variable is visible in the app (when a task has made a modification that must be visible in the application), and the performance is correspondingly reduced (or higher than synchronized).
However, it is important to note that volatile only ensures that the same piece of memory is being manipulated and does not guarantee the atomicity of the operation. So volatile is generally used to declare simple type variables so that they are atomic, meaning that some simple assignment and return operations are guaranteed to be uninterrupted. However, when the value of the variable is determined by its own last decision, the effect of volatile is invalidated, which is determined by the nature of the volatile keyword.
So be cautious when volatile, and never assume that all operations of the variable with the volatile modifier are atomic and no longer require the Synchronized keyword.

2.ThreadLocal

First threadlocal and the local thread do not have a dime relationship, not a special thread, it is just a thread of local variables (in fact, a map), threadlocal for each thread that uses the variable to provide a separate copy of the variable, So each thread can change its own copy independently, without affecting the copy of the other thread. This is done in the way of space-time (contrary to synchronized), at the expense of memory, which greatly reduces the performance cost of thread synchronization (such as synchronized) and reduces the complexity of thread concurrency control.
Personally think the more typical example is the use of threadlocal in the source code of Android about Looper, but also contains the basic usage of threadlocal, the specific code is as follows:

 Public classLooper {Private Static FinalString TAG = "Looper"; //Sthreadlocal.get () would return null unless you ' ve called prepare ().Private Static FinalThreadLocal sthreadlocal =NewThreadLocal (); ......  Private StaticLooper Mmainlooper =NULL; ......   Public Static Final voidprepare () {if(Sthreadlocal.get ()! =NULL) {     Throw NewRuntimeException ("Only one Looper could be created per thread"); } sthreadlocal.set (NewLooper ()); }  ......   Public Static Final voidPreparemainlooper () {prepare ();    Setmainlooper (Mylooper ());  ......  } Private synchronized Static voidSetmainlooper (Looper Looper) {mmainlooper=Looper;}  Public synchronized Static FinalLooper Getmainlooper () {returnMmainlooper;} ......   Public Static FinalLooper Mylooper () {return(Looper) Sthreadlocal.get ();} ......  }

However, it is important to note that although both threadlocal and synchonized are used to solve multi-threaded concurrent access, there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a lock is used so that a variable or block of code can be accessed by only one thread at a time. Instead, Threadlocal provides a copy of the variable for each thread, so that each thread accesses the same object at a certain time, isolating data sharing from multiple threads. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads. That is, synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads. Therefore, threadlocal is not a substitute for synchronized,synchronized's wider function range (synchronization mechanism).

3.synchronized

Synchronized keyword is the use of the lock mechanism of Java automatic implementation, there are generally synchronous method and synchronous code block two ways. All objects in Java automatically contain a single lock (also known as a monitor), and when any of its synchronized methods are called on an object, the object is locking (a task can get the lock of the object multiple times, the count is incremented), and before the thread returns from the method, All other threads within the object that are to be called synchronized in the class will be blocked. Of course there is also a lock for each class (as part of the class object), so you know the ^.^.
The last thing to note is that synchronized is the safest way to sync, and any other way is risky, and of course the price is the biggest.

"Go" Summary of 3 keywords (volatile, ThreadLocal, synchronized) easily confused in Java multithreaded programming

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.