简体   繁体   中英

Can volatile be eliminated by Java compiler optimizations

Can the optimizations performed by the Java compiler (version 5 or later) remove the "volatile" declaration of a variable?

More precisely, can a volatile variable be turned into a non-volatile variable in any of the following cases:

  • if there is no multithreading, ie if an application never uses more than one thread?

  • if a volatile variable is written by one thread but never accessed by any other thread?

  • if a volatile variable is read by several threads but never modified (read only, no writes)?

The volatile keyword requires that certain guarantees are satisfied when reading and writing the variable. It doesn't really make sense to talk about "removing the declaration"—no, that can't happen, because the only way that makes sense would be if the compiler ignored the declaration in your source code.

But if you are running the code in a context (eg, single-threaded) where you couldn't tell that the runtime is actively working to meet those requirements, it is permissible for the runtime to skip that extra work.

Of your examples, the only case that might be determined at compile-time is a variable that is only written, and never read. In that case, the compiler could skip writes (if a variable is written, and no one is around to read it, does it make a sound?), but the the Java Memory Model still makes some guarantees about happens-before relationships around writing a volatile variable, and those still have to be upheld, so it wouldn't make sense to optimize that away at compile-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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