本文持續更新,匯總 Java 進階開發必備的核心知識點,涵蓋 JVM 內存模型、參數配置、集合框架線程安全特性及實戰編碼技巧。
設計思想:按對象存活時間分代管理——新創建對象分配於新生代,經多次 GC 仍存活則晉升至老年代。老年代 GC 頻率較低,顯著減少全堆掃描開銷,提升回收效率。
堆內存劃分:


關鍵參數解析:
-Xms10240m:初始堆內存 10GB-Xmn5120m:新生代 5GB-XX:SurvivorRatio=3:Eden : From : To = 3:1:1,Survivor 總計 2048MB
| 非線程安全 | 線程安全對應類 | 備註 |
|---|---|---|
| HashMap | Hashtable / ConcurrentHashMap | 推薦 ConcurrentHashMap |
| ArrayList | Vector / Collections.synchronizedList | Vector 為早期實現 |
| StringBuilder | StringBuffer | StringBuffer 方法同步 |
| — | Properties | 繼承 Hashtable,天然線程安全 |

public class SortMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("1d", 4);
map.put("2b", 3);
map.put("3a", 1);
map.put("4c", 2);
System.out.println("原始數據:");
map.forEach((k, v) -> System.out.println(k + ":" + v));
// 轉 List 排序
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
// 按 Key 排序
Collections.sort(list, Comparator.comparing(Map.Entry::getKey));
System.out.println("按 Key 排序:");
list.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
// 按 Value 排序
Collections.sort(list, Comparator.comparing(Map.Entry::getValue));
System.out.println("按 Value 排序:");
list.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}
}
核心思路:將 entrySet 轉為 List,利用 Collections.sort + Comparator 實現多維度排序。Java 8+ 可用 Lambda 表達式進一步簡化代碼。