import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class AutoRemoveCollection<T> implements Collection<T> {
private static ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
private Collection<T> collection;
private long timeout;
private TimeUnit timeUnit;
public AutoRemoveCollection(Collection<T> collection, long timeout, TimeUnit timeUnit) {
this.collection = collection;
this.timeout = timeout;
this.timeUnit = timeUnit;
}
@Override
public boolean add(T t) {
boolean add = collection.add(t);
scheduledExecutorService.schedule(() -> {
remove(t);
},timeout,timeUnit);
return add;
}
@Override
public boolean addAll(Collection<? extends T> c) {
boolean b = collection.addAll(c);
scheduledExecutorService.schedule(() -> {
removeAll(c);
},timeout,timeUnit);
return b;
}
public static void close() throws Exception {
scheduledExecutorService.shutdown();
}
//其他Overide...
}
一个简单的测试
import org.junit.Test;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class MyTest {
@Test
public void test01() throws Exception {
AutoRemoveCollection<Object> objects = new AutoRemoveCollection<>(new HashSet<>(), 2, TimeUnit.SECONDS);
objects.add(1);
System.out.println(objects.contains(1));
Thread.sleep(3000);
System.out.println(objects.contains(1));
//app shutdown 当应用和模块停用时,关闭线程池
AutoRemoveCollection.close();
}
}
测试结果:
true
false