简体   繁体   English

volatile关键字与同步Java块的重要性是什么?

[英]What is the importance of the volatile keyword with synchronized java blocks?

请问谁能告诉我Java中的volatile关键字是什么,它的主要功能,如何在同步块中使用它,如果将其从块中完全删除,会发生什么?

Let's start with what's a volatile variable in java: 让我们从Java中的volatile变量开始:

Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory Java中的Volatile关键字用作Java编译器和Thread的指示符,它们不缓存此变量的值并始终从主内存读取它

so what is the benefit of reading the variable value from the memory, consider the following sample code: 因此,从内存中读取变量值有什么好处,请考虑以下示例代码:

public class Singleton{
private static volatile Singleton _instance; //volatile variable 

public static Singleton getInstance(){

if(_instance == null){
        synchronized(Singleton.class){
          if(_instance == null)
          _instance = new Singleton();
        }

}
return _instance;

}

in the previous sample: 在上一个示例中:

1) We are only creating instance one time 1)我们只创建一次实例

2) We are creating instance lazily at the time of first request comes. 2)我们在第一个请求到来时懒洋洋地创建实例。

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null. 如果我们不将_instance变量设为volatile,那么正在创建Singleton实例的线程将无法通信其他线程,该实例将一直创建,直到它从Singleton块中出来为止,因此,如果线程A正在创建Singleton实例且刚好在创建之后如果失去了CPU,所有其他线程将无法看到_instance的值不为null,他们将认为_instance的值仍为null。

Conclusion: 结论:

volatile keyword will be more useful. volatile关键字会更有用。 When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. 当多个线程使用相同的变量时,每个线程将拥有该变量的本地缓存副本。 So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. 因此,当更新值时,它实际上是在本地缓存中而不是在主变量存储器中进行更新。 The other thread which is using the same variable doesn't know anything about the values changed by the another thread 使用相同变量的另一个线程对另一个线程更改的值一无所知

Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. Java中的Volatile关键字用作Java编译器和Thread的指示符,它们不缓存此变量的值,而始终从主内存中读取它。

What will happen if we remove it from a synchronized block? 如果将其从同步块中删除会怎样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM