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 68 of 100

Can you explain the different types of memory models available in Java and how they differ?

πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

In Java, a memory model is a set of rules that governs the behavior of multi-threaded programs. The memory model defines how threads interact with memory and how changes made by one thread are visible to other threads.

There are two types of memory models in Java: the original Java Memory Model (JMM) and the new Java Memory Model introduced in Java 9.

Original Java Memory Model (JMM) The original Java Memory Model (JMM) was introduced in Java 1.2 and defined the behavior of multi-threaded programs in terms of happens-before relationships. The happens-before relationship defines a set of ordering rules that ensure that the execution of one thread is visible to other threads in a consistent and predictable manner.

In the original Java Memory Model, the visibility of changes made to shared variables between threads is guaranteed by the use of synchronized blocks and methods. Any changes made to a shared variable inside a synchronized block or method are guaranteed to be visible to all other threads that subsequently enter a synchronized block or method on the same monitor.

New Java Memory Model The new Java Memory Model, introduced in Java 9, defines a stronger memory model that provides stronger guarantees for performance and security. The new memory model is based on the concept of variable access modes, which define the behavior of threads accessing shared variables.

The new Java Memory Model introduces three access modes for shared variables:

Plain Access: Plain access mode provides no guarantees about visibility or ordering of accesses. Volatile Access: Volatile access mode guarantees that all writes to a volatile variable are visible to all threads and are ordered with respect to other volatile variable accesses. Ordered Access: Ordered access mode provides stronger ordering guarantees than plain access mode, but weaker than volatile access mode.

The new memory model provides a set of APIs for working with shared variables in the different access modes. For example, the VarHandle API provides access to variables in the new memory model, and the MemoryScope API provides a way to specify the access mode for operations on shared variables.

Here is an example of how the new Java Memory Model can be used to work with shared variables using the VarHandle API:

import java.lang.invoke.VarHandle;

public class Example {
    private static int count = 0;
    private static final VarHandle COUNT\_HANDLE = 
        VarHandle
            .volatileVariableHandle(int.class, VarHandle.AccessMode.VOLATILE);

    public static void main(String[] args) throws Throwable {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                COUNT\_HANDLE.getAndAdd(Example.class, 1);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                COUNT\_HANDLE.getAndAdd(Example.class, 1);
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count: " + count);
    }
}

In this example, we use the VarHandle API to define a volatile variable for the count variable. We then create two threads that increment the count variable 100000 times each. Finally, we join the threads and print out the value of the count variable.

Overall, understanding the different types of memory models available in Java is important for writing correct and performant multi-threaded code. The original Java Memory Model provides simple and reliable guarantees for multi-threaded code, while the new Java Memory Model provides stronger performance and security guarantees.

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