Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Các collection class thread-safe trong Java

Thread-safe Collections (Legacy – synchronized)

Các class cũ (Java 1.0/1.1) synchronized mọi phương thức public:

  • Vector – dynamic array, synchronized
  • Stack – extends Vector, LIFO
  • Hashtable – Map synchronized, không cho null key/value
  • Properties – extends Hashtable, cho config

Nhược điểm: hiệu năng kém do lock toàn bộ object, API cũ.

Thread-safe Collections hiện đại (java.util.concurrent)

  • ConcurrentHashMap – Map high concurrency, segment locking (Java 8: CAS + synchronized per bucket)
  • CopyOnWriteArrayList – List thread-safe, read-heavy
  • CopyOnWriteArraySet – Set thread-safe
  • ConcurrentLinkedQueue – Queue non-blocking
  • BlockingQueue implementations: ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue...
  • ConcurrentSkipListMap/Set – Sorted, concurrent

Ví dụ Vector (Legacy)


import java.util.*;

public class VectorDemo {
    public static void main(String[] args) {
        Vector v = new Vector<>();
        v.add("A"); v.add("B"); v.add("C");
        System.out.println("Vector: " + v);
        v.remove(1);
        System.out.println("After remove: " + v);
    }
}

Kết quả: Vector: [A, B, C] → After remove: [A, C]

Ví dụ Stack


import java.util.*;

public class StackDemo {
    public static void main(String[] args) {
        Stack st = new Stack<>();
        st.push(5); st.push(7); st.push(9);
        System.out.println("Pop: " + st.pop()); // 9
        System.out.println("Peek: " + st.peek()); // 7
    }
}

Khuyến nghị

Ưu tiên dùng java.util.concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList...) thay vì Vector/Hashtable/Stack. Chỉ dùng legacy khi maintain code cũ.