what is volatile in java? with Example & Code

In this article, we will discuss on Volatile keyword of java. We will discuss, what is Volatile in java? Purpose of Volatile, How it works, Differences between volatile and synchronization, use case of Volatile, etc.

I. Introduction

A. Explanation of what is volatile in Java

The volatile keyword in Java is used to indicate that a variable’s value may be modified by multiple threads. When a variable is declared volatile, the Java Virtual Machine (JVM) will ensure that any thread that reads the variable will always see the most up-to-date value.

B. Purpose of using volatile keyword

The purpose of using volatile keyword is to ensure that multiple threads have access to the most recent version of a variable’s value. This can be particularly useful in multi-threaded environments where multiple threads may be accessing and modifying the same variables.

II. How volatile works?

A. Explanation of how volatile works in Java

When a variable is declared volatile, the JVM will ensure that any reads or writes to the variable are performed in a way that is visible to all threads. This means that when one thread writes to a volatile variable, the change will be immediately visible to any other thread that subsequently reads the variable.

B. Differences between volatile and non-volatile variables

Volatile variables are different from non-volatile variables in that they are always read from main memory and never from a CPU cache.

C. How volatile variables are handled by the JVM

When a thread reads a volatile variable, it reads the value from main memory, rather than from a CPU cache. This ensures that the thread always has the most up-to-date value for the variable.

III. Use cases of volatile

A. Examples of when to use volatile

One common use case for volatile is when multiple threads may be accessing and modifying the same variable, and it is important to ensure that all threads see the most recent version of the variable’s value.

Another use case is when you have a “stop” flag in your code, you can use volatile to make sure that the flag is seen by all the threads.

B. How volatile can be used to solve concurrency issues

Volatile can be used to solve concurrency issues by ensuring that multiple threads have access to the most recent version of a variable’s value. This can help to prevent issues such as race conditions, where multiple threads try to access and modify the same variable at the same time.

C. Best practices for using volatile

When using volatile, it’s important to keep in mind that it’s a weaker form of synchronization and it should not be used to replace synchronization or locks.

IV. Differences between volatile and synchronization

A. Explanation of the differences between volatile and synchronization

Volatile is a weaker form of synchronization, it only guarantees visibility but not atomicity, while synchronization guarantees both visibility and atomicity. Volatile can be used as a memory barrier, but it cannot be used to protect shared data from race conditions.

B. How volatile can be used in conjunction with synchronization

Volatile can be used in conjunction with synchronization to provide additional guarantees. For example, you can use a volatile boolean flag in conjunction with a lock to implement a thread-safe “stop” mechanism.

C. When to use volatile vs synchronization

Volatile should be used when you need to ensure that a variable’s value is visible to all threads, but you don’t need to protect it from race conditions. On the other hand, synchronization should be used when you need to ensure that a shared resource is accessed in a thread-safe manner, and you need to protect it from race conditions.

Example of a Volatile keyword, code with output

Yes, here is an example of using the volatile keyword in Java:

class Example {
    volatile int count = 0;  // Declaring a volatile variable

    public void incrementCount() {
        count++;
    }

    public static void main(String[] args) {
        Example obj = new Example();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> obj.incrementCount()).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Final count: " + obj.count);
    }
}

In this example, we have a class called Example which contains a volatile variable called count. A method called incrementCount() increments this count variable by 1. In the main method, we create 10 threads and each thread calls the incrementCount() method. Since the count variable is declared as volatile, the JVM ensures that every thread reads the most recent value of the count variable, even though the increment operation is not atomic.

The output of this code will be different every time it runs, but it should be close to 10 since all threads increment the count variable by 1. However, since the increment operation is not atomic, the final count may be less than 10.

Final count: 9

It’s worth mentioning that, if we didn’t use the volatile keyword, the final count would be unpredictable and could be much less than 10 because the JVM can optimize the code by caching the value of the count in a register, and if we don’t use volatile the JVM is not guaranteed to flush the updated value of the variable back to main memory, so the other threads may see stale values.

V. Conclusion

A. Summary of key points

The volatile keyword in Java is used to indicate that a variable’s value may be modified by multiple threads. The JVM ensures that any thread that reads the variable will always see the most up-to-date value. The purpose of using volatile is to ensure that multiple threads have access to the most recent version of a variable’s value, and it can be used to solve concurrency issues by ensuring that multiple threads have access to the most recent version of a variable’s value.

B. Best practices for using volatile

When using volatile, it’s important to keep in mind that it’s a weaker form of synchronization and it should not be used to replace synchronization or locks.

C. Recommendations for using volatile in Java

Volatile should be used when you need to ensure that a variable’s value is visible to all threads, but you don’t need to protect it from race conditions. When it comes to synchronization, it should be used when you need to ensure that a shared resource is accessed in a thread-safe manner, and you need to protect it from race conditions.

Learn More:

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment