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

Core Java · Advanced · question 58 of 100

What is a volatile keyword in Java? How is it used?

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

The volatile keyword in Java is used to indicate that a variable’s value may be modified by multiple threads and should be synchronized among them. When a variable is declared as volatile, any read or write of that variable will be done from the main memory, rather than from a thread’s own cache. This ensures that the latest value of the variable is always visible to all threads.

In Java, when a variable is not declared as volatile, each thread may have its own cached copy of that variable, so updates by one thread may not be immediately visible to other threads. This can lead to race conditions and other synchronization issues. Using volatile ensures that updates to the variable are immediately visible to all threads, and can prevent such issues.

Here is an example of using volatile in Java:

public class Counter {
    private volatile int count;
    
    public void increment() {
        count++;
    }
    
    public int getCount() {
        return count;
    }
}

In this example, the count variable is declared as volatile, which ensures that updates to it are immediately visible to all threads that access it. The increment method increments the count by 1, and the getCount method returns the current count value.

It’s worth noting that volatile only ensures visibility of the variable’s value among threads, but it does not guarantee atomicity of operations on that variable. If multiple threads are performing operations on a volatile variable, it is possible for race conditions and other synchronization issues to occur. To ensure atomicity of operations, synchronization or the use of atomic classes like AtomicInteger may be necessary.

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

All 100 Core Java questions · All topics