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
| Phương thức | Input | Output | Giữ thứ tự |
|---|---|---|---|
| synchronizedSet | Set | Set | Không |
| synchronizedSortedSet | SortedSet | SortedSet | Có (theo comparator) |
| synchronizedNavigableSet | NavigableSet | NavigableSet | Có + điều hướng (lower, higher...) |