×

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of a class by several threads is not problematic. Both primitive types and objects are compatible with the volatile keyword. The volatile keyword always reads the variable's value from the main memory rather than caching it. Classes and methods cannot be combined with the volatile keyword.

Suppose there are two threads for a class. If the two threads are run on two different processors, and one thread modifies the variable’s value, it does not change in one line. It affects the code usability and creates inconsistency in data.

Syntax

class Test  
{  
static volatile int var =13;  
// volatile keyword make changes to the variable if  change occurs in any of the thread
} 

Advantages of Volatile Keyword

  • If we want to declare long and double variables automatically, we can use the volatile keyword.
  • Read and write operations on volatile keywords that are atomic.
  • Memory consistency error is reduced.
  • Object reference of volatile keyword is null
  • Other threads can see volatile keywords
  • If you do not share the variables between two threads, then it is not required to use the volatile keyword.
  • Volatile keyword memory is read from the main memory

Volatile vs Synchronised

VolatileSynchronised
Volatile is applicable to only keywordsSynchronised is applicable only to methods.
Mutual exclusion states that only one thread or process can run a vital part of code at once.  The synchronised keyword in Java ensures visibility and mutual exclusion.
Other threads are able to see changes made to shared data by one thread.  Only one thread can enter the block and its modifications will be reflected in the main memory if we synchronise the blocks of threads that modify the value of the shared variable. All other threads will be blocked and put to sleep if they attempt to enter the block concurrently.

Use of Volatile Keyword

public class Volatile
{  
private final static int no_of_threads = 2 ;  
public static void main ( String [ ] args ) throws InterruptedException  
{  
VolatileData vd = new VolatileData ( ) ;     // ----volatile_data class  ovject is created - - - - -
Thread [ ] t = new Thread [ no_of_threads ] ;     // Thread array is created with name t   
for ( int i = 0 ; i < no_of_threads ; ++i )  
 t [ i ]  = new ThreadVolatile ( vd ) ;  
for ( int i = 0 ; i < no_of_threads ; ++i )  
t [ i ] . start ( ) ;                 // -- all reader threads  are started ---
for ( int i = 0 ; i < no_of_threads; ++i)  
t [ i ] . join ( ) ;                  // --all threads are in wait state--  
}  
}


VolatileData.java
// Class with the  name VolatileData is created to store the volatile variable data
public class VolatileData  
{  
private volatile int counter1 = 0 ;   
public int getCounter1 ( )   
{  
return counter1 ;  
}  
public void increaseCounter1 ( )   
{  
++counter1 ;      // counter variable value is increased by one 
}  
}

ThreadVolatile.java

// class with the name thread_volatile is created and using inheritance extending the properties of the thread class
public class ThreadVolatile extends Thread   
{  
//  A final keyword is declared as volatile
private final VolatileData data1 ;  
public ThreadVolatile ( VolatileData data1 )   
{  
this.data1 = data1 ;         
}  
@Override  
// run method is used to start the threads
public void run ( )  
{  
int old_value = data1 . getCounter1 ( ) ;  
System . out . println ( " [ Thread " + Thread . currentThread ( ) . getId ( ) + " ] :  Old value = =" + old_value ) ;  
data1 . increaseCounter1 ( ) ;  
int new_value = data1 . getCounter1 ( ) ;  
// Printing the thread
System . out . println ( " [ Thread is " + Thread . currentThread ( ) . getId ( ) + " ] :  New value = " + new_value ) ;  
}  
}

Output

Volatile keyword in Java

Related Topics

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.