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

Cách làm cho Collection thread-safe trong Java

Class Collections trong package java.util cung cấp các phương thức tĩnh để tạo ra các collection thread-safe (an toàn cho đa luồng). Các phương thức này trả về các wrapper synchronized xung quanh collection gốc.

Các phương thức synchronized chính

STTPhương thức & Mô tả
1static <T> Collection<T> synchronizedCollection(Collection<T> c)
Trả về collection thread-safe backed bởi collection được chỉ định.
2static <T> List<T> synchronizedList(List<T> list)
Trả về list thread-safe backed bởi list được chỉ định.
3static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
Trả về map thread-safe backed bởi map được chỉ định.
4static <T> Set<T> synchronizedSet(Set<T> s)
Trả về set thread-safe backed bởi set được chỉ định.
5static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
Trả về sorted map thread-safe.
6static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
Trả về sorted set thread-safe.

Ví dụ minh họa

import java.util.Collection;
import java.util.Collections;
import java.util.Vector;

public class CollectionThreadSafe {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<String>();
        vector.add("JavaFx");
        vector.add("Java");
        vector.add("WebGL");
        vector.add("OpenCV");
        System.out.println(vector);
        
        Collection<String> synchronizedVector = Collections.synchronizedCollection(vector);
        System.out.println("Synchronized " + synchronizedVector);
        synchronizedVector.add("CoffeeScript");
    }
}

Kết quả

[JavaFx, Java, WebGL, OpenCV]
Synchronized [JavaFx, Java, WebGL, OpenCV]

Lưu ý quan trọng: Khi duyệt qua collection synchronized, bạn phải đồng bộ hóa thủ công trên đối tượng wrapper để tránh race condition:

synchronized (synchronizedVector) {
    Iterator<String> it = synchronizedVector.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

Đối với hiệu suất cao hơn trong môi trường đa luồng, hãy cân nhắc sử dụng các concurrent collections từ package java.util.concurrent như ConcurrentHashMap, CopyOnWriteArrayList.