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.
solved How to avoid using volatile in Java