自定义一个 AutoRemoveCollection

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 implements Collection {

    private static ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

    private Collection collection;
    private long timeout;
    private TimeUnit timeUnit;

    public AutoRemoveCollection(Collection 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 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 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

你可能感兴趣的:(自定义一个 AutoRemoveCollection)