Re: volatile



Timo Nentwig schrieb:
Timo Stamm wrote:
| The volatile modifier requests the Java VM to always access the shared
| copy of the variable so the its most current value is always read. If
| two or more threads access a member variable, AND one or more threads
| might change that variable's value, AND ALL of the threads do not use
| synchronization (methods or blocks) to read and/or write the value,
| then that member variable must be declared volatile to ensure all
| threads see the changed value.

Yes...

Okay, some shorter pseudo-code:

thread1{
int value;

void modify(){ value++; }
void print() {System.out.println( value ); }
}

thread2{
thread1.modify();

// IMHO I don't need volatile here:
thread1.print();

// but I wouldneed it here:
System.out.println(thread1.value);
}

I don't think you need "volatile" in this case. There are no /concurrent/ modifications: thread2 does the modification (through thread1.modify), and reads the value /afterwards/.


As far as I understand it, this would be a more appropriate example:

thread1 {
int value;
while (true) {
value++;
}
}

thread1 {
while (true) {
System.out.println(thread1.value);
}
}


value should be marked volatile because the JVM could keep a copy in a register and thread2 would never know the modified value.


Timo Stamm
.