Monday 13 July 2015

Volatile Keyword



java-volatile-1.png

Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory.

The volatile keyword is used to mark a variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

The volatile keyword is used to say to the JVM "Warning, this variable may be modified in another Thread".

Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile keyword forces the thread to update the original variable for each variable.


1.  If two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use synchronization in that case to guarantee that the reading and writing of the variable is atomic.

2. The volatile keyword could be used on every kind of variable, either primitive or objects.

3. A variable can use final or volatile modifier at a single time.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...