Thread safety means that concurrent execution by multiple threads preserves an object's correctness and consistency. Accidental sharing through static mutable fields is a common warning sign: state intended for one object or operation can become shared across threads. section 3.11
A static queue leaks work between walkers
TreeWalker stores its pending nodes in a static queue. One instance works correctly alone, but two concurrent instances consume the same queue, allowing nodes from one traversal to leak into another. Keep mutable traversal state instance-local rather than static. section 3.11
Reduce accidental sharing and make suspicious state visible:
- Avoid static nonfinal fields and mutable objects in static fields unless the shared state is deliberate. section 3.11
- Use distinctive IDE highlighting and warnings for static fields updated from nonstatic contexts. section 3.11
- When several threads are expected, add integration tests that emulate concurrent use; do not assume every warning is incorrect. section 3.11
- Choose thread-safe mutable objects when sharing requires them, but avoid their overhead when thread safety is unnecessary. section 3.11
class TreeWalker {
private static final Queue<TreeNode> toProcess =
new ArrayDeque<>();
TreeWalker(TreeNode root) {
toProcess.add(root);
}
TreeNode nextNode() {
TreeNode next = toProcess.poll();
if (next != null) {
toProcess.addAll(next.getChildren());
}
return next;
}
}
Inspect the minimal TreeWalker implementation whose static queue creates accidental cross-instance sharing. section 3.11
Figure 3.5 A possible execution when using TreeWalker from two threads concurrently. As the toProcess variable is accidentally shared, nodes may leak from one thread to another.
Trace a possible two-thread execution in which shared pending nodes move between traversals. section 3.11







