Java Memory Model
28 questions in 8 subtopics.
Happens-before
What is the happens-before relation in the Java Memory Model, and list the main rules that create it.What outcomes are possible here and how do you fix it?class Task {
boolean ready;
int value;
void writer(){
value = 42;
ready = true;
}
void reader(){
while (!ready) {} System.out.println(value);
}
}
String.hashCode() caches its result in a non-volatile field without synchronization, and this is considered correct. Why, and why are such benign data races dangerous to copy in your own code?A senior engineer on your team wrote a lock-free cache that relies on careful reasoning about happens-before, and claims it is 20% faster than using ConcurrentHashMap. It will be used by many services. How do you decide whether to accept it?Java defined its memory model in the language specification, revised by JSR-133 in Java 5, years before C and C++ standardised theirs in 2011. What did this give the Java ecosystem, and what should engineers in your organisation still be taught about it?Volatile semantics
What does volatile guarantee and what does it not guarantee? Is count++ on a volatile int thread-safe?How are volatile reads and writes implemented on x86 compared with ARM, and what areVarHandle's weaker access modes for?A worker loop is controlled by a stop flag:private boolean running = true;
public void stop(){
running = false;
}
public void run(){
while (running) {
doWork();
}
}
VarHandle access modes (plain, opaque, acquire/release, volatile) that resemble the memory orders of C++11. Why did Java expose these weaker modes, and should application teams in your organisation use them?Visibility and reordering
Give the main reasons a write by one thread may not be seen, or may be seen out of order, by another thread in Java.A service passes all tests on developer laptops and x86 servers, but after moving to ARM-based cloud instances, it shows rare corrupted state in an in-memory cache. Code review finds fields shared between threads without volatile or locks. Explain the connection and your plan.Your company plans to move most Java services to ARM instances for cost reasons. As the architect responsible, how do you assess the concurrency risk and plan the migration?Safe publication
What does safe publication mean, and list the ways to publish an object safely in Java.class Listener {
Listener(EventSource src) {
src.register(this);
this.handlers = loadHandlers();
}
public void onEvent(Event e) {
handlers.forEach(h -> h.handle(e));
}
}
NullPointerException at startup. Explain.A service reloads a configuration map every minute from a remote store and many request threads read it. Design the reload so readers always see a consistent configuration without locking on each read.Your platform's shared libraries contain many lazily initialised singletons, caches and registries written by different people. What rules for initialisation and publication would you set so that libraries are correct when used from many threads?Final field semantics
What does the Java Memory Model guarantee about final fields, and when does that guarantee break?A teammate proposes making a value class immutable by making its fields private and not providing setters, but not marking them final, saying final adds nothing. Another proposes using reflection to set a final field during deserialization. How do you respond?Your platform shares value objects between threads widely and wants a standard for them. A team uses records such as recordOrder(String id, List<Line> lines) and assumes they are immutable. Define the standard.Double-checked locking
What is wrong with this lazy singleton, and give two correct alternatives.class Config {
private static Config instance;
static Config get() {
if (instance == null) {
synchronized (Config.class) {
if (instance == null) instance = new Config();
}
}
return instance;
}
}
Word tearing and long/double
Are reads and writes of long and double atomic in Java? What about references and other primitives, and what is word tearing?A metrics class stores the last request timestamp in a plain long field written by request threads and read by a monitoring thread. A colleague says this is fine on 64-bit servers. What risks remain and what would you use?The JLS still allows non-volatile long and double writes to be non-atomic, a rule that dates from 32-bit hardware, even though most JVMs today run on 64-bit machines. What does this say about specifications versus implementations, and how should code be written?Thread confinement
What is thread confinement, and give three ways Java code achieves it, including one where the framework does it for you. Why does confinement remove the need for synchronization?A Spring Boot service moved to virtual threads, and memory use rose sharply; heap dumps show millions ofThreadLocal values holding buffers and date formatters. In another service, user ids from one request appear in another request's logs. Explain both problems.Your platform library uses ThreadLocal for request context (user, tenant, trace id) across 100 services, and teams now use virtual threads, CompletableFuture and reactive code. What context propagation design would you standardise?No question matches these choices.