|
| 1 | +--- |
| 2 | +id: d54a4e9f-74b9-4579-84a3-2541fe7b4272 |
| 3 | +slug: "legacy-synchronized-collections" |
| 4 | +title: "Legacy synchronized collections to modern alternatives" |
| 5 | +category: "collections" |
| 6 | +difficulty: "intermediate" |
| 7 | +jdkVersion: "5" |
| 8 | +oldLabel: "Legacy synchronized collection" |
| 9 | +modernLabel: "Concurrent Collections API" |
| 10 | +oldApproach: "Hashtable" |
| 11 | +modernApproach: "ConcurrentHashMap" |
| 12 | +oldCode: |- |
| 13 | + Hashtable<String, Session> sessions = new Hashtable<>(); |
| 14 | + sessions.put(id, session); |
| 15 | +modernCode: |- |
| 16 | + ConcurrentMap<String, Session> sessions = new ConcurrentHashMap<>(); |
| 17 | + sessions.put(id, session); |
| 18 | +summary: "Replace Vector and Hashtable with collections selected for actual mutability and concurrency needs." |
| 19 | +explanation: "Vector and Hashtable synchronize every operation through legacy APIs. Modern\ |
| 20 | + \ code should normally use ArrayList or HashMap for thread-confined data, and purpose-built\ |
| 21 | + \ concurrent collections when shared mutation is required." |
| 22 | +whyModernWins: |
| 23 | +- icon: "🎯" |
| 24 | + title: "Intentional concurrency" |
| 25 | + desc: "The chosen type documents whether sharing is expected." |
| 26 | +- icon: "⚡" |
| 27 | + title: "Better scalability" |
| 28 | + desc: "ConcurrentHashMap avoids a single table-wide lock for normal access." |
| 29 | +- icon: "🧩" |
| 30 | + title: "Modern APIs" |
| 31 | + desc: "Works naturally with current collection and concurrent-map operations." |
| 32 | +support: |
| 33 | + state: "available" |
| 34 | + description: "Widely available since JDK 5 (September 2004)" |
| 35 | +prev: "collections/unmodifiable-collectors" |
| 36 | +next: "strings/string-isblank" |
| 37 | +related: |
| 38 | +- "collections/immutable-map-creation" |
| 39 | +- "collections/copying-collections-immutably" |
| 40 | +- "concurrency/lock-free-lazy-init" |
| 41 | +tags: |
| 42 | +- collections |
| 43 | +- concurrency |
| 44 | +docs: |
| 45 | +- title: "ConcurrentHashMap" |
| 46 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html" |
| 47 | +- title: "ConcurrentMap" |
| 48 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ConcurrentMap.html" |
0 commit comments