package com.yunfeiyun.agmp.common.core.domain.model;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantLockList<T> {
    // 默认的大小
    private static final int DEFAULT_CAPACITY = 10;

    // 线程不安全的List
    private final List<T> array;

    public ReentrantLockList() {
        array = new ArrayList<>(DEFAULT_CAPACITY);
    }

    public ReentrantLockList(int initialCapacity) {
        if (initialCapacity > 0) {
            array = new ArrayList<>(initialCapacity);
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                    initialCapacity);
        }
    }

    // 读写锁
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();

    // 添加元素
    public void add(T t) {
        writeLock.lock();
        try {
            array.add(t);
        } finally {
            writeLock.unlock();
        }
    }

    // 删除元素
    public void remove(T t) {
        writeLock.lock();
        try {
            array.remove(t);
        } finally {
            writeLock.unlock();
        }
    }

    // 获取数据
    public T get(int index) {
        readLock.lock();
        try {
            return array.get(index);
        } finally {
            readLock.unlock();
        }
    }

    public int getSize() {
        readLock.lock();
        try {
            return array.size();
        } finally {
            readLock.unlock();
        }
    }

    static ReentrantLockList<String> reentrantLockList = new ReentrantLockList<>(20000);
}
