Nested Synchronized Wrapper Anti-Pattern
You'll learn why wrapping an already-synchronized collection in another synchronized wrapper is redundant and how to avoid this common mistake.
What Is the Anti-Pattern?
The nested synchronized wrapper anti-pattern occurs when you apply Collections.synchronizedList() (or similar methods) to a collection that's already thread-safe. This creates unnecessary layers of synchronization that add overhead without improving safety.
Think of it like putting a locked box inside another locked box—the inner lock already protects the contents, so the outer lock just makes access slower without adding security.
Common Mistakes
You might accidentally create nested wrappers in several ways:
// Anti-pattern: wrapping an already synchronized collection
List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> doubleWrapped = Collections.synchronizedList(list); // Redundant!
Or when converting between synchronized types:
Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());
// Anti-pattern: the map is already synchronized
Map<String, Integer> redundant = Collections.synchronizedMap(syncMap);
Why It's Problematic
Each synchronized wrapper adds locking overhead. Every method call must acquire and release a lock. With nested wrappers, you're acquiring multiple locks for a single operation, degrading performance without any benefit.
How to Avoid It
- Check the source: Know whether your collection is already synchronized before wrapping it
- Wrap once: Apply
Collections.synchronizedXxx()only to unsynchronized collections - Document clearly: If you're returning a synchronized collection from a method, document it so callers don't re-wrap it
Key Takeaway: Only wrap unsynchronized collections once with Collections.synchronizedXxx()—wrapping an already-synchronized collection creates redundant locking layers that hurt performance without improving thread safety.