synchronized (Atomic ordering visibility) volatile (atomicity visibility)
1.volatile essentially telling jvm current variable values in register (working memory) is uncertain, needs to be read from the main memory; synchronized current variable is locked, only the current thread can access the variables, other threads are blocking live.
2.volatile can only be used in a variable level; can be used in the synchronized variables, methods, and the class level.
3.volatile visibility can be achieved only modify variables, does not guarantee atomicity; synchronized and modifications can ensure visibility and atomic variables.
4.volatile will not cause obstruction thread; synchronized may cause obstruction thread.
Variable 5.volatile not labeled optimizing compiler; mark may be synchronized variable optimizing compiler.
Atomic: The so-called atomic operation refers not be interrupted thread scheduling mechanism operate; this operation once started, it runs to completion
For example: int i = 1; the statement is an atomic operation, because the execution of this sentence is the value of i is equal to a constant.
Anti Example: int i = 0; i ++; wherein i ++ not atomic, multithreading have security thread, i ++ actually divided into three steps, 1 reads the value of variable i; 2: for i of plus one operation; 3 and then the calculated value assigned to the variable i
synchronized: to ensure an atomic operation. 1, lock the main memory, 2, 3 the implementation, main memory is written to working memory. 4. Release lock
But an atomic mass different from the synchronized operation of the real sense, when executed is interrupted
Reason: Singleton
volatile instruction reordering prevented to ensure atomic
class Singleton {
private (volatile) static Singleton instance = null;
public static Singleton instance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null)
instance = new Singleton();//step1
}
}
return instance;
}
}
Ordering:
Visibility: When a thread modifies shared variables, other threads can see immediately that this modification
Get the latest value of the variable will be shared from the main memory when the thread gets the lock, the lock will be released when the shared variable synchronization to the main memory. Thereby, synchronized with visibility. Similarly, in the volatile analysis will lock instruction in the instruction by the addition in order to achieve visibility of memory. Thus, volatile have visibility
Reference: https: //www.jianshu.com/p/cf57726e77f2
、https://blog.csdn.net/weixin_45110404/article/details/90453221
https://blog.csdn.net/niexianglin_csdn/article/details/47361003