其中,使用了ReentrantReadWriteLock来保证对List的读写操作是线程安全的,并使用CopyOnWriteArrayList来避免使用锁时对整个List进行复制,从而提高并发性能。使用ScheduledExecutorService 来定期清空List。
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TimedClearList<E> {
private final List<E> list;
private final long clearInterval;
private final ScheduledThreadPoolExecutor scheduler;
private final ReentrantReadWriteLock lock;
public TimedClearList(long clearInterval) {
this.list = new CopyOnWriteArrayList<>();
this.clearInterval = clearInterval;
this.scheduler = new ScheduledThreadPoolExecutor(1);
this.lock = new ReentrantReadWriteLock();
this.scheduler.scheduleAtFixedRate(this::clear, clearInterval, clearInterval, TimeUnit.MILLISECONDS);
}
public boolean add(E e) {
lock.writeLock().lock();
try {
return list.add(e);
} finally {
lock.writeLock().unlock();
}
}
public E get(int index) {
lock.readLock().lock();
try {
return list.get(index);
} finally {
lock.readLock().unlock();
}
}
public int size() {
lock.readLock().lock();
try {
return list.size();
} finally {
lock.readLock().unlock();
}
}
public boolean contains(E e) {
lock.readLock().lock();
try {
return list.contains(e);
} finally {
lock.readLock().unlock();
}
}
public void clear() {
lock.writeLock().lock();
try {
list.clear();
} finally {
lock.writeLock().unlock();
}
}
public void shutdown() {
scheduler.shutdown();
}
}
使用案例
public static void main(String[] args) {
TimedClearList<Integer> timedClearList = new TimedClearList<>(5000); // 每 5 秒清空一次 List
timedClearList.add(1);
timedClearList.add(2);
timedClearList.add(3);
System.out.println(timedClearList.get(0)); // 输出 1
System.out.println(timedClearList.get(1)); // 输出 2
System.out.println(timedClearList.get(2)); // 输出 3
try {
Thread.sleep(6000); // 等待 6 秒,使得 List 被清空
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(timedClearList.size()); // 输出 0
timedClearList.add(4);
timedClearList.add(5);
System.out.println(timedClearList.get(0)); // 输出 1
System.out.println(timedClearList.get(1)); // 输出 2
try {
Thread.sleep(6000); // 等待 6 秒,使得 List 被清空
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(timedClearList.size()); // 输出 0
timedClearList.shutdown(); // 关闭 TimedClearList
}