Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How To Implement Volatile Keyword in Java?

Published on Aug 06,2019 8.5K Views

36 / 72 Blog from Java Core Concepts

Java is one programming that is blessed with plenty of features. In this article we will be exploring one such feature that is volatile keyword in Java. Following pointers will be covered in this article,

Moving on with this article on Volatile Keyword in Java.

A volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread-safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.

Example

class Test
{
static int var=5;
}

In the above example, assume that two threads are working on the same class. Both threads run on different processors where each thread has its local copy of var. If any thread modifies its value, the change will not reflect in the original one in the main memory. It leads to data inconsistency because the other thread is not aware of the modified value.

class Test
{
static volatile int var =5;
}

In the above example, static variables are class members that are shared among all objects. There is only one copy in the main memory. The value of a volatile variable will never be stored in the cache. All read and write will be done from and to the main memory.

Moving on with this article on Volatile Keyword in Java.

Difference between synchronization and volatile keyword

Volatile keyword is not a substitute of synchronized keyword, but it can be used as an alternative in certain cases. There are the following differences are as follows:

Volatile KeywordSynchronization Keyword
Volatile keyword is a field modifier.Synchronized keyword modifies code blocks and methods.
The thread cannot be blocked for waiting in case of volatile.Threads can be blocked for waiting in case of synchronized.
It improves thread performance.Synchronized methods degrade the thread performance.
It synchronizes the value of one variable at a time between thread memory and main memory.It synchronizes the value of all variables between thread memory and main memory.
Volatile fields are not subject to compiler optimization.Synchronize is subject to compiler optimization.

Moving on with this article on Volatile Keyword in Java.

Example:

public class VolatileTest {
private static final Logger LOGGER = MyLoggerFactory.getSimplestLogger();
private static volatile int MY_INT = 0;
public static void main(String[] args) {
new ChangeListener().start();
new ChangeMaker().start();
}
static class ChangeListener extends Thread {
@Override
public void run() {
int local_value = MY_INT;
while ( local_value < 5){
if( local_value!= MY_INT){
LOGGER.log(Level.INFO,"Got Change for MY_INT : {0}", MY_INT);
local_value= MY_INT;
}
}
}
}
static class ChangeMaker extends Thread{
@Override
public void run() {
int local_value = MY_INT;
while (MY_INT <5){
LOGGER.log(Level.INFO, "Incrementing MY_INT to {0}", local_value+1);
MY_INT = ++local_value;
try {
Thread.sleep(500);
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
}

Image- Volatile-Edureka

Thus we have come to an end of this article on ‘Volatile Keyword in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Implement Volatile Keyword in Java?

edureka.co