Java / Java 21 Coding Standards Interview Questions
How do you design a thread-safe class following Java 21 coding standards?
The standard starting point is to make the class immutable wherever possible - final fields set only in the constructor, no setters - since an immutable object is automatically thread-safe with no locking required, and records make this the default rather than something to opt into.
public record AccountSnapshot(String id, BigDecimal balance, Instant asOf) {} // immutable: safe to share across threads with zero synchronization
When mutable state is unavoidable, standards call for confining it behind a minimal, well-defined interface and protecting it with the narrowest synchronization that is correct - a single ReentrantLock or synchronized method around the actual state change, not scattered locking sprinkled across every method that happens to touch a field.
On virtual threads specifically, this means preferring non-blocking or short-held locks over long-held synchronized blocks, and validating the design under real concurrency with a stress-testing tool rather than relying on manual reasoning alone, since subtle visibility and ordering bugs are notoriously hard to spot by inspection.
More Related questions...