This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Volatile Keyworld Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Volatile Keyworld" Watch "Volatile Keyworld" New topic
Author

Volatile Keyworld

Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 253

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
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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: 253

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
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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: 3344

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: 385
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://aspose.com/file-tools
 
subject: Volatile Keyworld
 
Similar Threads
volatile example
volatile and static keywords
Synchronisation did not work.
Java thread question...
Thread and volatile