File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Volatile Keyworld Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Volatile Keyworld" Watch "Volatile Keyworld" New topic
Author

Volatile Keyworld

Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 219
As per my understanding, we use volatile keyword to make sure that all the threads access the value of that specific instance variable from main memory rather than local cache. In this case, value updated by one thread would be visible to all other threads as well. But I could not see this happening in the below example.



Each time, it prints Test Value : 0 while, as per my understanding, it should printTest Value : 10. Can someone please let me know where I have gap in my understanding.


Regards
Salil Verma
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9191
    
    2

There are two different instances of ExampleThread class. And the field testValue is an instance variable. So both the threads will have a different copy of the testValue field. Make testValue static and then see...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 219
Hey Ankit,

If I declare testValue as static member, it returns the Test Value : 10 irrespective of testValue being volatile or non volatile. Could you please explain the reason behind it ?

I am mainly trying to make an example where I could see the impact of volatile keyword.

Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9191
    
    2

Look at a tutorial like this to understand the actual use of volatile and this tutorial explains when you might use volatile keyword...
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3327

Thats a good link Ankit. Thanks!


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 377
I thnk volatile has no effect on static variable.

As far as i know volatile and transient modifiers applies to instance variable not to static variable.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Volatile Keyworld
 
Similar Threads
volatile example
Thread and volatile
volatile and static keywords
Synchronisation did not work.
Java thread question...