Giới thiệu về CopyOnWriteArrayList
CopyOnWriteArrayList là một biến thể an toàn cho luồng (thread-safe) của ArrayList. Tất cả các phép toán thay đổi cấu trúc (như add, set, remove) đều được thực hiện bằng cách tạo một bản sao mới của mảng gốc. Điều này làm cho việc lặp qua danh sách rất an toàn mà không cần đồng bộ hóa rõ ràng, phù hợp cho các tình huống "đọc nhiều, ghi ít".
Ví dụ minh họa
Dưới đây là các bước tạo một ứng dụng Android đơn giản để demo CopyOnWriteArrayList.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project, điền các thông tin cần thiết và chọn Empty Activity.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/actionEvent"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:textSize="40sp" />
</LinearLayout>
Chúng ta sử dụng một TextView để hiển thị nội dung của danh sách.
Bước 3: Viết logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.concurrent.CopyOnWriteArrayList;
public class MainActivity extends AppCompatActivity {
private CopyOnWriteArrayList<String> copyOnWriteArrayList;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
copyOnWriteArrayList = new CopyOnWriteArrayList<>();
final TextView actionEvent = findViewById(R.id.actionEvent);
// Thêm các phần tử
copyOnWriteArrayList.add("sai");
copyOnWriteArrayList.add("ram");
copyOnWriteArrayList.add("krishna");
copyOnWriteArrayList.add("prasad");
copyOnWriteArrayList.add("ram"); // Phần tử trùng lặp được phép
// Hiển thị danh sách
actionEvent.setText(copyOnWriteArrayList.toString());
}
}
Lưu ý: Code trên đã được cập nhật để sử dụng thư viện AndroidX (androidx) và Generics (<String>) để an toàn kiểu dữ liệu hơn so với ví dụ gốc.
Chạy ứng dụng
Kết nối thiết bị thật hoặc chạy emulator. Nhấn Run trong Android Studio. Màn hình sẽ hiển thị danh sách các phần tử: [sai, ram, krishna, prasad, ram].