I'm checking this great post on java fences, in which fences are used for following example, to ensure that concurrent thread can always read latest value updated from other threads:
// CPU 0:
void shutDownWithFailure(void)
{
failure = 1; // must use SOB as this is owned by CPU 1
SFENCE // next instruction will execute after all SOBs are processed
shutdown = 1; // can execute immediately as it is owned be CPU 0
}
// CPU1:
void workLoop(void)
{
while (shutdown == 0) { ... }
LFENCE // next instruction will execute after all LOBs are processed
if (failure) { ...}
}
My question is, what's the advantage of using fences against volatile
.
Taking above example, if I make both failure
and shutdown
volatile, it should achieve the same?
CodePudding user response:
I would say, it's all described in the JEP 171 that is linked to that question, in the "Motivation" section at the top. To sum it up: it is meant to provide a documented way to access these mechanisms and to provide further implementations and extensions of the classes for concurrent access.
Doesn't mean to use them is always an advantage over volatile
.