Re: volatile
- From: "Mike Schilling" <mscottschilling@xxxxxxxxxxx>
- Date: Fri, 31 Mar 2006 18:13:44 GMT
"Timo Stamm" <timo.stamm@xxxxxxxx> wrote in message
news:442d5ab4$0$7760$9b4e6d93@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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/.
Without either volatile or synchronization, there's no guarantee thread 1
will see a change made in thread 2; thread 1 might hold onto its previously
cached value indefinitely.
By the way
value++
should be a red flag. If two threads can both execute it, volatile isn't
good enough, becsue you have no guarantee about how
fetch value
increment
store the result in value
get interleaved. Nothing less than
synchronize(lock)
{
value++;
}
is reliable.
.
- References:
- volatile
- From: Timo Nentwig
- Re: volatile
- From: Timo Stamm
- Re: volatile
- From: Timo Nentwig
- Re: volatile
- From: Timo Stamm
- volatile
- Prev by Date: Re: Class Loading on Different Opperating Systems
- Next by Date: Re: Reading HDD serialNo
- Previous by thread: Re: volatile
- Next by thread: Problems with using JFormattedTextField
- Index(es):
Relevant Pages
|
|