自定義一個 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<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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 文章來自:http://blog.csdn.net/mj813/article/details/52451355 ...
    好大一只鵬閱讀 9,215評論 2 126
  • 1.測試與軟件模型 軟件開發生命周期模型指的是軟件開發全過程、活動和任務的結構性框架。軟件項目的開發包括:需求、設...
    Mr希靈閱讀 21,987評論 7 278
  • 1.測試與軟件模型 軟件開發生命周期模型指的是軟件開發全過程、活動和任務的結構性框架。軟件項目的開發包括:需求、設...
    宇文臭臭閱讀 6,751評論 5 100
  • 1.問:你在測試中發現了一個 bug ,但是開發經理認為這不是一個 bug ,你應該怎樣解決。 首先,將問題提...
    qianyewhy閱讀 9,292評論 4 123
  • 也許,我的愛不適合現代的規則。有人說,青春太短,有感覺就要揮霍,并不代表我沒有勇氣,去說愛你。當我抱著你在我的懷里...
    始于是問閱讀 243評論 0 1