Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

44
LINES

< > BotCompany Repo | #1033563 // MultiSleeper

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (10643L/59K).

sclass MultiSleeper is ISleeper, AutoCloseable {
  MultiSetMap<Timestamp, Runnable> entries = treeMultiSetMap();
  new RestartableCountdown countdown;
  
  private void check {
    var time = nextWakeUpTime();
    var action = firstValue(entries);
    countdown.setTargetTime(time == null ? 0 : time.sysTime(), r {
      Set<Runnable> toCall;
      synchronized(MultiSleeper.this) {
        toCall = entries.get(time);
        entries.remove(time);
        check();
      }
      pcallFAll(toCall);
    });
  }
  
  private synchronized void removeEntry(Timestamp targetTime, Runnable action) {
    entries.remove(targetTime, action);
  }
  
  // API
  
  synchronized Timestamp nextWakeUpTime() {
    ret firstKey(entries);
  }
  
  public synchronized Sleeping doLater(Timestamp targetTime, Runnable r) {
    if (r == null || targetTime == null) null;
    targetTime = max(targetTime, tsNow());
    entries.put(targetTime, r);
    check();
    ret new Sleeping(targetTime, r) {
      close {
        removeEntry(targetTime, r);
      }
    };
  }
  
  close {
    dispose countdown;
  }
}

Author comment

Began life as a copy of #1015557

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, ekrmjmnbrukm, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1033563
Snippet name: MultiSleeper
Eternal ID of this version: #1033563/13
Text MD5: d66bad59222765209dc6d307d14b8006
Transpilation MD5: f530b41a8251265bf1ed041b3131b5b0
Author: stefan
Category: javax / timers
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2023-03-22 14:55:41
Source code size: 1133 bytes / 44 lines
Pitched / IR pitched: No / No
Views / Downloads: 211 / 386
Version history: 12 change(s)
Referenced in: [show references]