Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile type modifier

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
Can someone explain what exactly is the job of the volatile type modifier with a simple example?

Regards
Mansukhdeep

 
Henry Wong
author
Marshal
Pie
Posts: 21504
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Virendrasinh Gohil
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic