简体   繁体   中英

How to avoid using volatile in Java

I have two threads sharing the same variable of type boolean. I discovered that I have to use volatile to guarantee the value is always read from main memory. But now I want to get rid of this volatile identifier, how can I achieve that? Is it true that I easily can extract my boolean property into an object. As the reference to object never change the thread will always access the correct value from the main memory. Will this work?

如果您不喜欢该关键字,您也可以使用 AtomicBoolean 代替 - 这也将允许写访问也是线程安全的

I have to use volatile to guarantee the value is always read from main memory

That is not how volatile work. volatile is used to build a happens-before relation ship:

This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

—— From the doc .

But now I want to get rid of this volatile identifier, how can I achieve that?

Like said in another answer, you can use AtomicBoolean . Or, add synchronized block around the code reading/writing this variable. Or use some other mechanism , as well as they can build a happens-before relation ship between reading and writing this varibale in different threads.

Is it true that I easily can extract my boolean property into an object. As the reference to object never change the thread will always access the correct value from the main memory. Will this work?

No. The reference do not change, this does not mean the fresh object is always visible to other reading threads after it is updated.

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