At some point we needed to have an array with volatile elements in java.
We knew that such beast is not found in the java world. So we searched the Internet and found the answers that are so wrong, and introduce so obscure threading bugs that the guys who provided them would better hide them and run immediately to fix their buggy programs...
The first one is Volatile arrays in Java. They suggest such solution:
volatile int[] arr = new int[...]; ... arr[4] = 100; arr = arr;
The number two: What Volatile Means in Java
A guy assures that this code works:
Fields:
int answer = 0; volatile boolean ready = false;
Thread1:
answer = 42; ready = true;
Thread2:
if (ready) { print(answer); }
They are very wrong! Non volatile access can be reordered by the implementation. See Java's Threads and Locks:
The rules for volatile variables effectively require that main memory be touched exactly once for each use or assign of a volatile variable by a thread, and that main memory be touched in exactly the order dictated by the thread execution semantics. However, such memory actions are not ordered with respect to read and write actions on nonvolatile variables.
They probably thought of locks when they argued about volatiles:
a lock action acts as if it flushes all variables from the thread's working memory; before use they must be assigned or loaded from main memory.
P.S. They would better recommend AtomicReferenceArray.
Remember Me
a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u