WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Concurrency · Intermediate · question 28 of 100

How does the volatile keyword affect multi-threaded code?

📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

In Java, the volatile keyword is used to indicate that a variable’s value may be modified by multiple threads, and that changes to the variable should be immediately visible to all threads. When a variable is declared as volatile, the Java memory model ensures that any thread accessing the variable sees the most up-to-date value.

The volatile keyword is useful in multi-threaded code because without it, different threads may see different values of the same variable due to differences in how the variable is cached in memory. This can lead to race conditions and other synchronization issues.

Here’s an example of how the volatile keyword can be used in Java:

public class Example {
    private volatile boolean running = true;

    public void stop() {
        running = false;
    }
    
    public void run() {
        while (running) {
            // do some work
        }
    }
}

In this example, the running variable is declared as volatile because it is modified by one thread (the stop method) and read by another thread (the run method). Without the volatile keyword, the run method may not see the updated value of running after the stop method is called, which could cause the run method to continue running indefinitely.

With the volatile keyword, however, the Java memory model ensures that changes to the running variable are immediately visible to all threads. This ensures that the run method will stop running as soon as the stop method sets running to false.

Overall, the volatile keyword is a useful tool for managing concurrency in Java. It provides a way to ensure that changes to shared variables are immediately visible to all threads, which can help prevent race conditions and other synchronization issues. However, it should be used with care, as improper use of the volatile keyword can lead to subtle bugs and performance issues.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview — then scores it.
📞 Practice Java Concurrency — free 15 min
📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

All 100 Java Concurrency questions · All topics