Forums Register Login

Volatile Keyworld

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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...
+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
Look at a tutorial like this to understand the actual use of volatile and this tutorial explains when you might use volatile keyword...
+Pie Number of slices to send: Send
Thats a good link Ankit. Thanks!
+Pie Number of slices to send: Send
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.
You showed up just in time for the waffles! And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1229 times.
Similar Threads
volatile example
volatile and static keywords
Synchronisation did not work.
Java thread question...
Thread and volatile
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:43:58.