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

Java Concurrency · Expert · question 74 of 100

What is the JMM (Java Memory Model) and how does it affect multi-threaded code?

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

The JMM (Java Memory Model) is a specification that describes how threads in a Java program interact with the memory. It defines the rules that ensure the visibility and atomicity of operations performed by multiple threads on shared memory.

The JMM guarantees that each thread has a consistent view of the shared memory, regardless of the underlying hardware and operating system. Specifically, it defines the ordering of reads and writes to shared memory, and the synchronization mechanisms used to coordinate access to shared memory.

In multi-threaded code, the JMM affects how threads access and modify shared objects. Without proper synchronization, threads may see stale or inconsistent values, leading to race conditions, deadlocks, and other concurrency bugs. The JMM provides the tools for avoiding these issues by specifying how threads should interact with shared memory.

In Java, synchronization can be achieved using the synchronized keyword, locks, atomic variables, and other concurrency primitives provided by the Java API. These mechanisms ensure that memory operations are properly synchronized between threads, and that threads can access shared memory in a consistent and predictable manner.

Here’s an example code snippet that shows the use of the synchronized keyword to ensure thread safety:

public class Counter {
    private int count;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

In this example, the increment and getCount methods are synchronized using the synchronized keyword. This ensures that only one thread can access these methods at a time, preventing race conditions and ensuring that the count is incremented and returned correctly.

Overall, the JMM is an important concept in Java multi-threading that helps ensure the correctness and reliability of concurrent programs.

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