This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
volatile variables will be reconciled by every thread that uses them, each time each thread assign values to them. A non volatile variable reconciled with the main memory whenever the compiler thinks it's good to do so. Please, correct me if I'm wrong.
http://www.m-w.com/ There is a book called Effective Java by Joshua Bloch that explains this. I'll try to explain it as best I can. A thread will keep a local copy of a variable and then update the variable in main memory with its own value at its own will. When a variable is declared volatile, it makes the thread update (reconcile its own copy of) the variable to main memory each time it writes to it.
The second is more efficient because you don't need the lock to set bar. [ March 26, 2003: Message edited by: Garrett Smith ]
reconcile: to restore friendly relations between, to cause to coexist in harmony, to make or show to be compatible, to make one account consistent with another, to settle a disagreement
A variable is any location within a program that may be stored into. This includes not only class variables and instance variables but also components of arrays. Variables are kept in a main memory that is shared by all threads. Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a program, it operates on these working copies. The main memory contains the master copy of every variable. There are rules about when a thread is permitted or required to transfer the contents of its working copy of a variable into the master copy or vice versa. JLS 17.1
As described in �17, the Java programming language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. These working copies need be reconciled with the master copies in the shared main memory only at prescribed synchronization points, namely when objects are locked or unlocked. 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. The Java programming language provides a second mechanism, volatile fields, that is more convenient for some purposes. A field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested. JLS 220.127.116.11
[ March 26, 2003: Message edited by: Marlene Miller ]