This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I read a document which say Volatile Modifiers, are not cached by the JVM. When ever a volatile variable value is required by a thread it will access directly from the variable itself (without using the JVM cache)..
Volatile: Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. For example a Variable might be read from Cache and not update the content if it has been changed by another thread. Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all. Making the Variable Volatile will ensure that the compiler will get the content of the variable every time it is used and not cache its content. If not used Carefully this modifier might introduce bugs..
is my understanding is right ???... can you please share me in which real time scenarios we will use volatile modifiers....
You only use it in a multi-threaded environment. A simple example: Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread (like the event thread in AWT / Swing or the main thread). If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile.
Any variable can live in RAM, in Cache or in the registers on the chip. When a method finishes, the value may be stored in any of those plaecs in case it is needed again; if not it is moved back from register to cache to RAM. If two threads require access to a variable, they might pick it up from RAM, but there might be a more "recent" or "up-to-date" version in cache or a register. So(if I remember correctly) "volatile" means that methods must only use the "RAM" version of a variable, and when they have finished they must write their result back in RAM.
So the RAM version of a "volatile" variable is always the most "recent."
I believe that it is unfortunate that the document used "cache" -- as people assumes that it is the hardware cache. I don't think it does.
The memory subsystems, along with the L1/L2 caches, should be able to keep everything in sync, and provide the latest versions. IMHO, when the document says cache, I think it means that it will not delay writes of register to memory, or assumes that the register has the latest version.
IOWs, don't use registers to cache the value -- I don't think it was referring to the hardware caches.