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

65
LINES

< > BotCompany Repo | #1024883 // SeenAndQueue

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

Libraryless. Click here for Pure Java version (3834L/24K).

// synchronized
sclass SeenAndQueue<A> implements Iterable<A> {
  Set<A> seen = syncSet();
  L<A> queue = syncLinkedList();
  Int max; // stop after this many elements if not null
  
  transient L onAddedToQueue = syncList(); // L<Runnable|voidfunc(A)>
  transient L<Runnable> onQueueEmpty = syncList();

  // queue handler  
  transient ReliableSingleThread rst;
  
  *() {}
  *(Runnable handler) { rst(handler); }
  
  bool add(A a) {
    if (a == null || maxReached() || !seen.add(a)) false;
    queue.add(a);
    pcallFAll(onAddedToQueue, a);
    true;
  }
  
  void addAll(Iterable<A> l) { fOr (A a : l) add(a); }
  
  A popQueue() {
    ping();
    synchronized(queue) {
      A a = syncPopFirst(queue);
      if (a != null && empty(queue))
        pcallFAll(onQueueEmpty);
      ret a;
    }
  }
  
  // ends when queue is empty
  ItIt<A> queueIterator() {
    ret iteratorFromFunction_if0(() -> popQueue());
  }
  
  public ItIt<A> iterator() { ret queueIterator(); }
  
  void onAddedToQueue(O r) { onAddedToQueue.add(r); }
  
  ReliableSingleThread rst(Runnable handler) {
    if (rst != null) fail("rst already set");
    rst = ReliableSingleThread(handler);
    onAddedToQueue.add(rst);
    ret rst;
  }
  
  void cleanMeUp {
    cleanUp(rst);
    rst = null;
  }
  
  bool queueEmpty() { ret queue.isEmpty(); }
  bool idle() { ret queueEmpty() && !rstRunning(rst); }
  
  S stats() { ret l(seen) + " seen, " + l(queue) + " queued"
    + (max == null ? "" : ", max: " + max); }
  
  bool maxReached() { ret max != null && l(seen) + l(queue) >= max; }
  
  Set<A> asSet() { ret seen; }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1024883
Snippet name: SeenAndQueue
Eternal ID of this version: #1024883/20
Text MD5: 0d866036f99412a5839830d88c377d28
Transpilation MD5: 95e2c758f00a8475de106d803343891b
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-23 17:16:39
Source code size: 1662 bytes / 65 lines
Pitched / IR pitched: No / No
Views / Downloads: 281 / 783
Version history: 19 change(s)
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)