Volatile, ThreadLocal, synchronized and other 3 keyword differences

Source: Internet
Author: User
Tags prepare volatile

1.volatile

Volatile is primarily used to synchronize variables in multiple threads.
Under normal circumstances, to improve performance, each thread saves a variable in its main memory as a copy of the variable in its own memory at run time, but this makes it easy to have conflicting replica variables stored in multiple threads or inconsistent with the values of variables in the main memory.
And 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 for the read and write operations, in other words, it does not allow a copy of a variable different from the "main" memory area, so when the variable is changed, All the threads that call the variable get the same value, which ensures that the variable is visible in the application (when a task makes modifications that must be visible in the application), while the performance is correspondingly reduced (or higher than synchronized).
But note that volatile can only ensure that the operation is the same piece of memory, and does not guarantee the atomic nature of the operation. So volatile is generally used to declare simple type variables so that these variables are atomic, that is, some simple assignment and return operations will be ensured uninterrupted. However, when the value of the variable is determined by its own previous decision, the function of the volatile is invalidated, as determined by the nature of the volatile keyword.
So in volatile must be cautious, do not think that with volatile modified after all the operation of the variable is atomic operation, no longer need the synchronized keyword.

2.ThreadLocal

First threadlocal and 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 counterpart of other threads. In fact, this is in the space of time (contrary to synchronized), at the expense of memory, the single greatly reduce the thread synchronization (such as synchronized) the performance of the cost and reduce the complexity of the thread concurrency control.
The typical example is the use of threadlocal in the Android code for Looper and the basic usage of threadlocal, as follows:

public class Looper { 
private static final String TAG = "Looper";
 
Sthreadlocal.get () would return null unless for you ' ve called prepare (). 
private static final ThreadLocal sthreadlocal = new ThreadLocal (); 
 
...... 
 
private static Looper mmainlooper = null; 
 
...... 
 
public static final void prepare () { 
  if (sthreadlocal.get ()!= null) { 
    throw new runtimeexception (' Only one looper May is created per thread "); 
  } 
  Sthreadlocal.set (New Looper ()); 
} 
 
...... 
 
public static final void Preparemainlooper () { 
  prepare (); 
  Setmainlooper (Mylooper ()); 
 
  ...... 
 
} 
 
Private synchronized static void Setmainlooper (Looper looper) { 
  mmainlooper = looper; 
} 
Public synchronized static final Looper Getmainlooper () {return 
  mmainlooper; 
} 
 
...... 
 
public static final Looper Mylooper () {return 
  (Looper) sthreadlocal.get (); 
} 
 
...... 
 
}



However, it should be noted that although both threadlocal and synchonized are used to resolve multithreaded concurrent access, there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a variable or block of code can only be accessed by one thread at a time. The threadlocal provides a copy of the variable for each thread, so that each thread is not accessing the same object at a given time, isolating multiple threads from data sharing. 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. So threadlocal is not a substitute for Synchronized,synchronized's broader range of functions (sync mechanism).

3.synchronized

The Synchronized keyword is the Java uses the lock the mechanism to realize automatically, generally has the synchronization method and the synchronized code block two kinds of use way. All objects in Java automatically contain a single lock (also known as a monitor), and when any of its synchronized methods are invoked on an object, the object is lock (a task can acquire the lock of the object multiple times, and the count increments), and before the thread returns from the method, All other threads within the object that are marked as synchronized in the class are 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 one of the safest ways to sync, and there are risks in any other way, and of course the cost is greatest.


Turn from: http://www.jb51.net/article/62630.htm

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.