Hi,
i can't understand why are using volatile in java please explain with example
Printable View
Hi,
i can't understand why are using volatile in java please explain with example
The use of this keyword as part of dealing with thread interference and memory consistency errors is a discussed in the Synchronization section of Oracle's Tutorial. (It's in the last section on "Atomic Access", but the whole thing is worth reading. Also, perhaps, the surrounding chapter on "Concurrency").
The Java Language Specification also discusses examples in the section 8.3.1.4 volatile Fields.
First, the easy cases where you basically don't need volatile or any other synchronization mechanism:
1. volatile is not necessary– or in fact possible– for fields that are immutable.
2. volatile is not necessary for variables that are accessed by only one thread.
3. volatile is not suitable for complex operations where you need to prevent access to a variable for the duration of the operation: in such cases, you should use object synchronization or one of Java 5's explicit lock classes added.
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.
Volatile is just a keyword in java. This can be used only with the variable declaration.
Example : volatile int variable_name;
- This indicate that the variable can be modified asynchronously by more than one thread.
- For volatile variable, compiler guarantee that all the threads should see the same value of a specified variable.
- The value of this variable will never be cached thread-locally, all reads and writes will go straight to main memory.
Java is the best programing language. Java has a very bright scope in the programming field. There are many software companies on the market, which use this language for making software and games as well.