Scrivio Interview library

Java Memory Model

28 questions in 8 subtopics.

Happens-before

ConceptFoundations7 min read
What is the happens-before relation in the Java Memory Model, and list the main rules that create it.
CodingFoundations7 min read
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);
}
}
with writer and reader on different threads.
ConceptIntermediate7 min read
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?
LeadershipAdvanced7 min read
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?
ConceptPrincipal7 min read
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

ConceptFoundations6 min read
What does volatile guarantee and what does it not guarantee? Is count++ on a volatile int thread-safe?
InternalsIntermediate7 min read
How are volatile reads and writes implemented on x86 compared with ARM, and what are VarHandle's weaker access modes for?
CodingIntermediate7 min read
A worker loop is controlled by a stop flag:
private boolean running = true;
public void stop(){
running = false;
}
public void run(){
while (running) {
doWork();
}
}
The worker sometimes never stops. Explain and fix, and say whether volatile alone is always enough for stop flags.
ConceptPrincipal7 min read
Java 9 added 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

ConceptFoundations6 min read
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.
DebuggingIntermediate7 min read
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.
ScenarioAdvanced6 min read
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

ConceptFoundations6 min read
What does safe publication mean, and list the ways to publish an object safely in Java.
DebuggingFoundations6 min read
class Listener {
Listener(EventSource src) {
src.register(this);
this.handlers = loadHandlers();
}
public void onEvent(Event e) {
handlers.forEach(h -> h.handle(e));
}
}
Some events fail with NullPointerException at startup. Explain.
DesignIntermediate6 min read
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.
LeadershipAdvanced7 min 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

ConceptFoundations7 min read
What does the Java Memory Model guarantee about final fields, and when does that guarantee break?
ScenarioIntermediate7 min read
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?
DesignAdvanced7 min read
Your platform shares value objects between threads widely and wants a standard for them. A team uses records such as record Order(String id, List<Line> lines) and assumes they are immutable. Define the standard.

Double-checked locking

CodingFoundations6 min read
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;
}
}
ConceptIntermediate7 min read
Compare volatile double-checked locking, the holder-class idiom and eager initialisation for lazy singletons in terms of cost and use cases. What about lazily initialised per-instance fields?
LeadershipPrincipal9 min read
Double-checked locking was widely used and broken before Java 5, then fixed by new volatile semantics. Many codebases still contain variants. What does this history say about how organisations should treat clever concurrency idioms?

Word tearing and long/double

ConceptFoundations7 min read
Are reads and writes of long and double atomic in Java? What about references and other primitives, and what is word tearing?
ScenarioIntermediate6 min read
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?
ConceptPrincipal7 min read
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

ConceptFoundations7 min read
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?
DebuggingIntermediate8 min read
A Spring Boot service moved to virtual threads, and memory use rose sharply; heap dumps show millions of ThreadLocal values holding buffers and date formatters. In another service, user ids from one request appear in another request's logs. Explain both problems.
DesignAdvanced7 min read
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?