Emulating a memory barrier in Java to get rid of volatile reads

So basically you want the semantics of a volatile without the runtime cost.

I don't think it is possible.

The problem is that the runtime cost of volatile is due the instructions that implement the memory barriers in the writer and the reader code. If you "optimize" the reader by getting rid of its memory barrier, then you are no longer guaranteed that the reader will see the "seldomly written" new value when it is actually written.

FWIW, some versions of the sun.misc.Unsafe class provide explicit loadFence, storeFence and fullFence methods, but I don't think that using them will give any performance benefit over using a volatile.


Hypothetically ...

what you want is for one processor in a multi-processor system to be able to tell all of the other processors:

"Hey! Whatever you are doing, invalidate your memory cache for address XYZ, and do it now."

Unfortunately, modern ISAs don't support this.

In practice, each processor controls its own cache.