synchronized: mutual exclusion — chỉ một thread thực thi block, đảm bảo atomicity và happens-before semantics.
- Chi phí cao: lock contention, context switching.
volatile: chỉ đảm bảo visibility — thay đổi hiển thị ngay cho tất cả thread, nhẹ hơn. volatile KHÔNG atomic (count++vẫn không an toàn). - Dùng
synchronizedcho: critical section, compound operations, đảm bảo state consistency. - Dùng
volatilecho: flag boolean, immutable reference. - Hiện đại: dùng
AtomicInteger/ReentrantLockthay vì volatile cho atomicity.