Search code examples
javaconcurrencyvolatile

local memory visibility with volatile write


As I understood new java memory model mandates that access to volatile variables is not reordered with access to other variables and thus following code is correct:

Map configOptions;
char[] configText;
volatile boolean initialized = false;

// In Thread A
configOptions = new HashMap();
configText = readConfigFile(fileName);
processConfigOptions(configText, configOptions);
initialized = true;

// In Thread B
while (!initialized) 
  sleep();
// use configOptions 

so when initialized is set to true config options is already initialized, but is it visible? I mean is it already in main memory?


Solution

  • Yes. As of Java 5 accessing a volatile variable creates a memory barrier that effectively synchronizes copies of all cached variables with the main memory.

    This is known as Synchronization Piggybacking where a write on a non-synchronized variable uses subsequent synchronization on some other variable to update its value with the main memory.

    Also, read/write on a volatile is expensive. It's not recommended to make use of it to bail out of an infinite loop. If it's somehow unavoidable at least make use of a Thread.sleep() somewhere.

    References:
    Volatile piggyback. Is this enough for visiblity?