The usage and function of the keyword Volatile in multithreading


The shortcomings, I hope you can point out.


volatile keyword
public class SingleCase {
//双检锁的对象必须要用volatile修饰,不然因为指令重排导致第一个判断为空时,将未初始化的对象
//返回。
 private static volatile SingleCase instance2;

public static SingleCase getInstance2(){
    if(instance2 == null){
        synchronized(SingleCase.lass){
            if(instance2 == null){
                instance2 = new SingleCase();
            }
        }
    }
    return instance2;
}
}
The double-checked lock object must be modified with volatile, otherwise the uninitialized object will be returned when the first judgment is empty due to instruction rearrangement.
Previous Article thread-safe, other basic characteristics of the synchronized keyword (reentrant lock) example of a certain problem is how to ensure that created the object is fully initialized after instance2.
This is what I plan to study with everyone today. The above code is wrongly written, and the reason is wrong, because: instruction rearrangement optimization may cause the order of initializing a simple interest object and assigning the object address to the instance field to be different from the order written in the Java code above .
For example, when thread A creates a singleton object, before the constructor is called, it allocates memory space for the object and sets the object to the default value. At this time, thread A can assign the allocated memory address to the instance field, but the object may not have completed the initialization operation. Thread B calls the newInstance () method, and the result is to initialize the complete singleton object, which will cause the system to behave abnormally.
In order to solve the above problems, the instance field can be modified using the volatile keyword. The meaning of the volatile keyword here is to prohibit the reordering optimization of instructions (another role is to provide memory visibility ), so as to ensure that when the instance field is initialized, the singleton object has been fully initialized.

The role of the volatile keyword is to force the value of the variable from the public stack, not to obtain the value of the variable from the thread's private data stack.
Figure:

1. The keyword volatile is a lightweight implementation of thread synchronization, the performance is better than synchronized, and volatile can only be modified in variables, and synchronized can modify methods, code blocks, etc.
2、多线程访问volatile不会发生阻塞,而synchronized会发生阻塞。
3、volatile可以保证数据的可见性,但不可以保证原子性,而synchronized可以保证原子性,也可以间接保证可见性,因为他会将私有内存和公共内存中的数据做同步。
4、volatile解决 的是变量在多个线程之间的可见性,而synchronized解决的是多个线程之间访问资源的同步性。

发布了26 篇原创文章 · 获赞 0 · 访问量 9935

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/78747246