‘volatile’ keyword in java programming
‘volatile’ is a keyword used in java. It provides the changes that can be visible across the multiple threads. Most recent value is applicable for all threads.
Features:
- Visibility across the multiple threads.
- Even though Caching, atomicity cannot be done, it is light weight and overhead is reduced.
It makes latest value is read/written is visible.
Use ‘volatile’ keyword when the following condition occurs…
- Multiple threads access the same variable for reading and writing.
- Singleton patterns are used.
- Thread safety is needed.
Java program using ‘volatile’ keyword:
class SFlag {
private volatile
boolean f_run = true;
public void stop()
{
f_run = false;
// this statement makes this variable visible to all threads
}
public void doIt()
{
while (f_run)
{
// coding
blockto process the variable
System.out.println("Yes. It is Working!!!!...");
try {
Thread.sleep(250); // it makes the thread to pause for quarter a second
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("yes. it is stopped safely!");
}
public static void
main(String[] args) throws InterruptedException {
SFlag flag =
new SFlag();
// thread is
started
Thread ch =
new Thread(() -> flag.doIt());
ch.start();
System.out.println("The thread is running for 5 seconds");
// this
statement makes the thread to run for 5 seconds
Thread.sleep(5000);
// Stop the
thread
System.out.println("yes.As per your Request to stop...");
flag.stop();
// It makes
the thread to finish
ch.join();
System.out.println("Main thread is finished its work.");
}
}
Output:
C:\raji\blog>javac SFlag.java
C:\raji\blog>java SFlag
The thread is running for 5 seconds
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
Yes. It is Working!!!!...
yes.As per your Request to stop...
yes. it is stopped safely!
Main thread is finished its work.
Yes. The java program to use ‘volatile’ keyword is done.
Note: you cannot use this volatile variable for Dependent variables,
Compound operators in real time and Difficult synchronization problems.
Comments
Post a Comment