1. /**
    2. * 过期数据清理守护线程
    3. */
    4. private ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, r -> {
    5. Thread thread = new Thread(r, "Thread-Idempotency-deamon");
    6. thread.setDaemon(true);
    7. return thread;
    8. });

    使用

    1. private void initDeamon(){
    2. scheduler.scheduleWithFixedDelay(()->{
    3. for (Entry<String, Long> entry : dataMap.entrySet()) {
    4. if(System.currentTimeMillis() > entry.getValue()){
    5. dataMap.remove(entry.getKey());
    6. }
    7. }
    8. // 处理第三方清理逻辑
    9. deleteOther();
    10. }, 0, 5, TimeUnit.SECONDS);
    11. }
    1. private final ScheduledExecutorService executor;
    2. ...
    3. //create after the call above where MalformedURLException can be raised
    4. //avoids having to call shutdown in case the exception is raised
    5. executor = Executors.newSingleThreadScheduledExecutor(r -> {
    6. Thread ret = new Thread(r, "Executor for Watch " + System.identityHashCode(WatchConnectionManager.this));
    7. ret.setDaemon(true);
    8. return ret;
    9. });