×

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 Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.