简体   繁体   English

Java:易变变量访问

[英]Java : Volatile variable access

I am a little confuse about how volatile variable effectively accesses from "main" memory. 我对volatile变量如何有效地从“主”内存访问感到困惑。 How's it different from a variable (non-volatile) that has a local copy ? 与具有本地副本的变量(非易失性)有何不同? What's the typical workflow whenever multiple threads accesses a non-volatile vs a volatile variable ? 每当多个线程访问非易失性变量易失性变量时,典型的工作流程是什么? I mean how do they work behind the scene ? 我是说他们在幕后如何工作?

Let's say you have a variable that can be accessed by multiple threads. 假设您有一个可由多个线程访问的变量。

Thread 1 looks at the variable. 线程1查看变量。 Because looking at shared memory is more expensive than thread-local memory, it makes a copy of the variable. 因为查看共享内存比线程本地内存更昂贵,所以它会复制变量。 (Note that an object won't be copied, just its reference.) (请注意,不会复制对象,仅会复制其引用。)

Thread 2 looks at the same variable. 线程2查看相同的变量。 It decides to change the variable. 它决定更改变量。 But Thread 1 doesn't know it! 但是线程1不知道! Thread 1 is still using stale data. 线程1仍在使用陈旧数据。 This is a Very Bad Thing. 这是一件非常糟糕的事情。 By making it volatile , each thread must look at the original variable when accessing it. 通过使其volatile ,每个线程在访问它时都必须查看原始变量。 They aren't permitted to make local copies, so it won't get stale. 不允许他们制作本地副本,因此不会过时。

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

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