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

Cách sử dụng synchronizedSortedSet trong Android

Collections.synchronizedSortedSet()

Trả về wrapper đồng bộ hóa (thread-safe) cho SortedSet. Tất cả truy cập phương thức được synchronized. Phù hợp khi nhiều thread cùng đọc/ghi SortedSet.

Ví dụ: TreeSet thread-safe cho ListView

MainActivity.java

package com.example.syncsortedsetdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

public class MainActivity extends AppCompatActivity {
    EditText name;
    ArrayAdapter<String> adapter;
    ArrayList<String> dataList;
    SortedSet<String> sortedSet = new TreeSet<>();
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dataList = new ArrayList<>();
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

        findViewById(R.id.refresh).setOnClickListener(v -> {
            if (adapter != null) adapter.notifyDataSetChanged();
        });

        findViewById(R.id.save).setOnClickListener(v -> {
            String input = name.getText().toString().trim();
            if (!input.isEmpty()) {
                // Wrapper thread-safe
                Set<String> syncSet = Collections.synchronizedSortedSet(sortedSet);
                
                // Thêm vào set gốc (thông qua wrapper hoặc trực tiếp đều OK)
                syncSet.add(input);

                dataList.clear();
                dataList.addAll(syncSet);

                adapter = new ArrayAdapter<>(this, 
                    android.R.layout.simple_list_item_1, dataList);
                listView.setAdapter(adapter);

                Toast.makeText(this, "Đã thêm (thread-safe)", Toast.LENGTH_SHORT).show();
            } else {
                name.setError("Nhập tên");
            }
        });
    }
}

Quy tắc quan trọng khi dùng synchronizedSortedSet

// ĐÚNG: Đồng bộ hóa khi lặp (iteration)
Set<String> syncSet = Collections.synchronizedSortedSet(sortedSet);
synchronized (syncSet) {
    for (String s : syncSet) {
        // xử lý
    }
}

// SAI: Lặp không synchronized - có thể ConcurrentModificationException
for (String s : syncSet) { ... }

So sánh các wrapper đồng bộ hóa

Hiệu năng & Thay thế hiện đại

Collections.synchronizedXxx() dùng mutex đơn giản (coarse-grained lock) - chậm khi contention cao.

Thay thế tốt hơn (Java 5+):

  • ConcurrentSkipListSet - thread-safe, sorted, lock-free reads, hiệu năng cao.
  • CopyOnWriteArraySet - phù hợp đọc nhiều, ghi ít.
// Khuyến nghị cho Android hiện đại
Set<String> concurrentSet = new ConcurrentSkipListSet<>();
// Tự động sắp xếp, thread-safe, không cần synchronized block khi iterate

Kết luận

synchronizedSortedSet dùng cho code legacy hoặc yêu cầu đơn giản. Ứng dụng mới nên dùng ConcurrentSkipListSet.

Phương thứcInputOutputGiữ thứ tự
synchronizedSetSetSetKhông
synchronizedSortedSetSortedSetSortedSetCó (theo comparator)
synchronizedNavigableSetNavigableSetNavigableSetCó + điều hướng (lower, higher...)