aspose file tools*
The moose likes Beginning Java and the fly likes volatile type modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "volatile type modifier" Watch "volatile type modifier" New topic
Author

volatile type modifier

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Hi all
Can someone explain what exactly is the job of the volatile type modifier with a simple example?

Regards
Mansukhdeep


~ Mansukh
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18847
    
  40

The volatile modifier is used during declarations to specify that the variable is volatile. I don't know what you mean by "example" here, as the concept is ridiculously simple. Nothing to show here, just put the volatile keyword before instance and static variables that you want to be volatile.

Volatile variables have a few properties. Of which, the main ones are...

* Atomic access. Most variables are atomic during load and store, but with atomic they are guaranteed that the long and double are atomic too (using an internal JVM lock to accomplish this).

* No caching in registers. All read access are loaded directly from memory. All writes are flush directory to memory.

* Different ordering optimization. Or more correctly, the optimizer will try not to do code motion around volatile variables that can affect its behavior with other variables.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Virendrasinh Gohil
Ranch Hand

Joined: Jun 09, 2004
Posts: 46
Mansukhdeep Thind wrote:Hi all
Can someone explain what exactly is the job of the volatile type modifier with a simple example?

Regards
Mansukhdeep

The best use of volatile is visible in multi-threaded environment. Volatile, as Henry Wong said, are declared to be volatile while being access by multi-thread. There are two explanation to this now. One for Java 1.4 and second for Java 1.5.

Java 1.5 changed the definition of Volatile a little and internal implementation as well.

I will highly recommed reading these links:
http://www.javamex.com/tutorials/synchronization_volatile_java_5.shtml
http://www.javamex.com/tutorials/synchronization_volatile.shtml and
http://www.javamex.com/tutorials/synchronization_volatile_dangers.shtml
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Mansukhdeep Thind wrote:Can someone explain what exactly is the job of the volatile type modifier with a simple example

Also if you Search First , you will get many valuable replies including examples like this.


http://muhammadkhojaye.blogspot.com/
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: volatile type modifier