简体   繁体   中英

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?

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?

so when initialized is set to true config options is already initialized, but is it visible?

Yes . As soon you made it volatile is visible to all thread and read from main memory As per Java Language Specification

The Java programming language allows threads to access shared variables (§17.1). As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables. A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4). `

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