Nâng CaoJava iconJava

synchronized và volatile khác nhau thế nào? Khi nào dùng cái nào?

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 synchronized cho: critical section, compound operations, đảm bảo state consistency.
  • Dùng volatile cho: flag boolean, immutable reference.
  • Hiện đại: dùng AtomicInteger/ReentrantLock thay vì volatile cho atomicity.

Xem toàn bộ Java cùng filter theo level & chủ đề con.

Mở danh sách Java