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

60
LINES

< > BotCompany Repo | #1008561 // ConcurrentEvaluator

JavaX fragment (include)

sclass ConcurrentEvaluator {
  new L functions;
  L results = synchroList();
  ExecutorService executorService;
  O onNewResult; // Runnable or voidfunc(int)
  volatile bool cancelled;
  L<Thread> threads = synchroList();
  int coresToUse; // if 0, use coresToUse()
  
  void add(O f) { functions.add(f); }
  void addAll(Collection l) { functions.addAll(l); }
  
  void start() {
    executorService = Executors.newFixedThreadPool(coresToUse != 0 ? coresToUse : coresToUse());
    while (l(results) < l(functions)) results.add(null);
    for _i over functions: {
      final int i = _i;
      executorService.execute(r {
        threads.add(currentThread());
        try {
          results.set(i, pcallF(functions.get(i)));
          ping();
          onNewResult(i);
        } finally {
          threads.remove(currentThread());
        }
      });
    }
  }
  
  void onNewResult(int i) { if (!cancelled) pcallF(onNewResult, i); }
  
  L results() { ret cloneList(results); }
  
  void cancel {
    pcall {
      cancelled = true;
      executorService.shutdownNow();
      cancelThreads(cloneList(threads));
    }
  }
  
  void cancelAndWait {
    long time = sysNow();
    cancel();
    while (nempty(threads)) sleep(1);
    sysDone("Cancelling evaluators", time, 10);
  }
  
  bool done() { ret empty(threads); }
  
  void startWaitCleanUp {
    try {
      start();
      while (!done()) sleepSeconds(1);
    } finally {
      cancel();
    }
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1008561
Snippet name: ConcurrentEvaluator
Eternal ID of this version: #1008561/11
Text MD5: 2925adf721cf2ae3d5352937822b00f7
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-05-01 19:48:38
Source code size: 1515 bytes / 60 lines
Pitched / IR pitched: No / No
Views / Downloads: 456 / 1058
Version history: 10 change(s)
Referenced in: [show references]