AlgoMaster Logo

Java Memory Model - Quiz

Last Updated: December 6, 2025

1 min read

Java Memory Model Exercises

31 quizzes

1
Code Completion

Ensure a shared boolean flag write in one thread is visible to other threads immediately

java
1
volatile boolean running = ;

Click an option to fill the blank:

2
Code Completion

Safely publish a computed value to other threads using an atomic variable

java
1
AtomicInteger counter = new AtomicInteger();

Click an option to fill the blank:

3
Code Completion

Create a new object so it is allocated on the heap and referenced by a local variable

java
1
Person person = Person("Alice", 30);

Click an option to fill the blank:

4
Multiple Choice

In the Java Memory Model, which aspect describes when writes by one thread become observable to another?

5
Multiple Choice

Which Java keyword directly participates in defining happens-before relationships for mutual exclusion?

6
Multiple Choice

What is stored on the stack during a method call?

7
Multiple Choice

Which statement about heap memory in Java is correct?

8
Multiple Choice

When does the Java garbage collector mark an object as eligible for collection?

9
Multiple Choice

Which generation is primarily targeted by minor garbage collection events in a generational collector?

10
Multiple Choice

A common cause of memory leaks in Java applications is:

11
Multiple Choice

Which reference type allows an object to be reclaimed as soon as it is only referenced by that type, even if memory is not low?

12
Multiple Choice

Which statement about phantom references is correct?

13
Multiple Choice

Which tool is typically used to inspect heap dumps and identify memory leaks in Java?

14
Multiple Choice

Which JVM flag group enables detailed garbage collection logging on modern JVMs?

15
Sequencing

Order the steps to fix a visibility problem where a worker thread never stops because it does not see the latest value of a shared flag

Drag and drop to reorder, or use the arrows.

16
Sequencing

Order the steps performed by a typical mark-and-sweep garbage collector during a collection cycle

Drag and drop to reorder, or use the arrows.

17
Output Prediction

What is the output of this code related to heap vs stack allocation?

1class Counter {
2    int value;
3}
4
5public class HeapStackDemo {
6    public static void main(String[] args) {
7        Counter c1 = new Counter();
8        Counter c2 = c1;
9        c1.value = 5;
10        c2.value = 10;
11        System.out.println(c1.value);
12    }
13}
18
Output Prediction

What is the output illustrating happens-before with synchronized blocks?

1public class HappensBeforeDemo {
2    private static int value = 0;
3
4    public static void main(String[] args) throws Exception {
5        Object lock = new Object();
6        Thread writer = new Thread(() -> {
7            synchronized (lock) {
8                value = 42;
9            }
10        });
11        Thread reader = new Thread(() -> {
12            synchronized (lock) {
13                System.out.println(value);
14            }
15        });
16        writer.start();
17        writer.join();
18        reader.start();
19        reader.join();
20    }
21}
19
Output Prediction

What is the output showing that local primitives are on the stack and independent from heap objects?

1class Box {
2    int value;
3}
4
5public class StackIndependence {
6    public static void main(String[] args) {
7        Box box = new Box();
8        box.value = 3;
9        int local = box.value;
10        box.value = 7;
11        System.out.println(local);
12    }
13}
20
Output Prediction

What is the output of this code demonstrating that unreachable objects are collected logically, not immediately?

1public class ReachabilityDemo {
2    static class Node {
3        int id;
4        Node(int id) { this.id = id; }
5    }
6
7    public static void main(String[] args) {
8        Node node = new Node(1);
9        node = new Node(2);
10        System.out.println(node.id);
11    }
12}
21
Output Prediction

What is the output regarding weak references after clearing the strong reference (assuming GC may clear it)?

1import java.lang.ref.WeakReference;
2
3public class WeakRefDemo {
4    public static void main(String[] args) {
5        Object strong = new Object();
6        WeakReference<Object> weak = new WeakReference<>(strong);
7        strong = null;
8        Object ref = weak.get();
9        System.out.println(ref != null);
10    }
11}
22
Bug Spotting

Identify the bug causing a memory leak risk when using a listener in a long-lived manager

Click on the line(s) that contain the bug.

java
1
public class ListenerManager {
2
    private static java.util.List<Runnable> listeners = new java.util.ArrayList<>();
3
 
4
    public void register(Runnable listener) {
5
        listeners.add(listener);
6
    }
7
 
8
    public void clearAll() {
9
        // TODO: later
10
    }
11
}
23
Bug Spotting

Find the bug in this code that intends to stop a worker thread using a shared flag

Click on the line(s) that contain the bug.

java
1
public class StopWorker {
2
    private static boolean running = true;
3
 
4
    public static void main(String[] args) throws Exception {
5
        Thread t = new Thread(() -> {
6
            while (running) {
7
                // do work
8
            }
9
        });
10
        t.start();
11
        Thread.sleep(100);
12
        running = false;
13
    }
14
}
24
Matching

Match each memory-related concept with its correct description

Click an item on the left, then click its match on the right. Click a matched item to unmatch.

25
Matching

Match each Java reference type with its typical use case

Click an item on the left, then click its match on the right. Click a matched item to unmatch.

26
Fill in the Blanks

Complete the code so a background thread periodically checks a volatile flag and stops when requested

java
1
public class VolatileFlagDemo {
2
private static volatile boolean = true;
3
4
public static void main(String[] args) throws InterruptedException {
5
Thread worker = new Thread(() -> {
6
while () {
7
// simulate work
8
}
9
});
10
worker.start();
11
Thread.sleep(100);
12
= false;
13
}
14
}

Click an option to fill blank 1:

27
Fill in the Blanks

Complete the code to allocate an object on the heap and store its reference in a local variable

java
1
public class HeapExample {
2
static class Person {
3
String name;
4
Person(String name) { this.name = name; }
5
}
6
7
public static void main(String[] args) {
8
p = Person("Alice");
9
System.out.println(p.name);
10
}
11
}

Click an option to fill blank 1:

28
Fill in the Blanks

Complete the code so a map used as a cache does not prevent keys from being garbage collected

java
1
import java.util.Map;
2
import java.util.WeakHashMap;
3
4
public class CacheDemo {
5
private final Map<Object, String> cache = new <>();
6
7
public void put(Object key, String value) {
8
cache.put(key, value);
9
}
10
11
public String get(Object key) {
12
return cache.(key);
13
}
14
}

Click an option to fill blank 1:

29
Fill in the Blanks

Complete the code to create a soft reference used for a memory-sensitive cache entry

java
1
import java.lang.ref.;
2
3
public class SoftCacheEntry {
4
private final SoftReference<byte[]> dataRef;
5
6
public SoftCacheEntry(byte[] data) {
7
this.dataRef = new SoftReference<>();
8
}
9
10
public byte[] get() {
11
return dataRef.get();
12
}
13
}

Click an option to fill blank 1:

30
Hotspot Selection

Click the line that is most likely to cause a memory leak by holding references too long

Click on the line to select.

java
1
import java.util.ArrayList;
2
import java.util.List;
3
 
4
public class LeakDemo {
5
    private static final List<byte[]> cache = new ArrayList<>();
6
 
7
    public static void main(String[] args) {
8
        for (int i = 0; i < 100; i++) {
9
            byte[] data = new byte[1024 * 1024];
10
            cache.add(data);
11
        }
12
    }
13
}
31
Hotspot Selection

Click the line where the visibility guarantee for the shared flag is established

Click on the line to select.

java
1
public class VisibilityFix {
2
    private static volatile boolean stopped = false;
3
 
4
    public static void main(String[] args) {
5
        Thread t = new Thread(() -> {
6
            while (!stopped) {
7
                // work
8
            }
9
        });
10
        t.start();
11
    }
12
}

Premium Content

Subscribe to unlock full access to this content and more premium articles.