File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes volatile variables doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "volatile variables doubt" Watch "volatile variables doubt" New topic
Author

volatile variables doubt

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
I read this : "The volatile keyword is used on variables that may be modified simultaneously by other threads. This warns the compiler to fetch them fresh each time, rather than caching them in registers. This also inhibits certain optimisations that assume no other thread will change the values unexpectedly. Since other threads cannot see local variables, there is never any need to mark local variables volatile. You need synchronized to co-ordinate changes to variables from different threads, but often volatile will do just to look at them. "


How is it different from golbal/static variables ?
Rajesh Nagaraju
Ranch Hand

Joined: Nov 27, 2003
Posts: 50
golbal/static variables - Threads use a cached copy as you have mentioned.. hence in the run method it might not reflect the changes on the variable by other thread's changes on the variables in the run method.

volatile : Uses a fresh copy of the variable and hence changes due to other threads will be reflected in the volatile variable
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
What's a global variable? I know what it means in C, but does it actually exist in Java?
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
The volatile modifier does not affect variable scope or visibility. Rather,
it tells the compiler to create only a single, "master copy" object for this
variable. This implies, of course, that there can be other copies in memory.
Although allowed by the Java specification to speed things up, these extra
copies are invisible to the programmer.

Jim ... ...


BEE MBA PMP SCJP-6
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
Could someone please explain the content in " "

class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}
"This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j."
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

Jim Hoglund wrote:Rather, it tells the compiler to create only a single, "master copy" object for this variable. This implies, of course, that there can be other copies in memory. Although allowed by the Java specification to speed things up, these extra
copies are invisible to the programmer.


These "copies" are located in the hardware caches (L1, L2, etc.) and the processor registers. There are no copies on the computer physical memory as it doesn't get you anything.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
From Sun's "Java Programming Language, fourth edition" ""[V]olatile variables
are most often used for simple flags to indicate something has occurred, or for
writing lock-free algorithms that [use] atomic variables... [Volatile] extends the
basic automicity guarantee to cover long and double variables." That the simple
flags used are atomic is essential.

Below, also from the book: Since dataReady is volatile, it is guaranteed to Thread-1
that new Data() "happens-before" dataReady is updated to true. In turn, this assures
that Thread-2 can process 'd' only after Thread-1 has completed its work. Jim ... ...
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
"golbal/static variables - Threads use a cached copy as you have mentioned.. hence in the run method it might not reflect the changes on the variable by other thread's changes on the variables in the run method." what does cached copy mean here ?
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
In this situation, cached means that for better performance the JVM is managing more than
one copy of a variable. When one copy is changed, the others do not reflect the change until
somewhat later. This delay can cause problems for a multi-threaded application. This is where
"volatile" should be used as it prevents the multiple copies.

Jim ... ...
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

jose chiramal wrote:"golbal/static variables - Threads use a cached copy as you have mentioned.. hence in the run method it might not reflect the changes on the variable by other thread's changes on the variables in the run method." what does cached copy mean here ?


As mentioned, the cache copies are in the memory caches (L1, L2, etc.) and processor registers. This is actually not a Java thingy. Volatile variables, and the issues associated with them, applies to all modern computers.

BTW, assuming that you are still in school... given a chance to take a "computer architecture" course, I would highly recommend it. This course should teach you everything about the subject. And good schools generally teach this course in assembly language too ...

Henry
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
1. There are no global variables in Java

2. Static variables are class variables. That is, when you declare a variable as static, there is one variable for all instances of the class - not one variable for each instance. All instances share this single variable.

3. A variable declared as volatile is a regular instance variable except that the compiler will not store temporary instances of the variable when processing. For example, if you have a long-running function that you want to stop by external means (a user wants to stop it or an admin wants to stop all occurrences of the executing function), you can do it this way:

a. Declatre a class Calculate with an instance boolean bStop

b. Declare a function in the Calculate class called longRunning(). In this function create a (long running) loop that each time through the loop checks the bStop variable and ends if bStop is true.

c. When running the function longRunning() in one thread, from another thread set the bStop instance variable to true. Note: be sure you are acting on the same instance in both threads. This theoretically should stop the longRunning() function.

d. Here's the problem. If you don't adorn the bStop variable as transient, the compiler, when starting the longRunning() function may copy the value of bStop and use the copy in the loop. When another thread changes the value of bStop, the long running loop will not see the change (because it is using the copy) and continue processing. Setting bStop as transient tells the compiler to use the bStop variable in the long running loop rather than a copy of bStop. The loop will then end when bStop is set to true.

4. Note that declaring a variable as volatile does not obviate the need to synchronize access to it from multiple threads.
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Tom : Very god points, and welcome to JavaRanch ... ...

Jim ... ...
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18129
    
    8

Tom Reilly wrote:d. Here's the problem. If you don't adorn the bStop variable as transient...

You meant to say volatile in this paragraph, didn't you?
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Paul Clapham wrote:
Tom Reilly wrote:d. Here's the problem. If you don't adorn the bStop variable as transient...

You meant to say volatile in this paragraph, didn't you?


Yes, thank you. I meant volatile
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: volatile variables doubt
 
Similar Threads
Volatile Confusion
Confusion in threads
Create Thread-Safe Classes on Multiprocessor Hardware
Thread
volatile and static keywords