• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Volatile Keyworld

 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats a good link Ankit. Thanks!
 
Siva Masilamani
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic