Java ConcurrentHashMap.compute: อัปเดตค่าต่อคีย์แบบ atomic
น้องกายEngineering
นับเคาน์เตอร์ต่อคีย์แบบหลายเธรดแล้วกลัว get+put แข่งกันใช่ไหมครับ — ใช้ ConcurrentHashMap.compute (หรือ merge / computeIfAbsent) ให้แมปจัดการ atomic ต่อคีย์
จุดที่พลาดบ่อย:
- ฟังก์ชันใน
computeควรสั้นและไม่บล็อก — อย่าเรียก I/O ยาวในนั้น - คืน
null= ลบคีย์ computeIfAbsentเหมาะสร้างค่าครั้งแรก,mergeเหมาะบวกรวมค่า
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<>();
m.compute("hits", (k, v) -> v == null ? 1 : v + 1);
m.compute("hits", (k, v) -> v == null ? 1 : v + 1);
assert m.get("hits") == 2 : m;
System.out.println("ok");
}
}
Recap
- เลิกแพทเทิร์น get-modify-put บน ConcurrentHashMap
- เลือก compute / merge / computeIfAbsent ตามเคส
- อ่านAPI ConcurrentHashMap.compute