sclass ProbabilisticScheduler implements IProbabilisticScheduler, Steppable { TreeSetWithDuplicates entries = new(byProbability()); bool verbose; double cutoffProbabilityOnAdd = 0; double cutoffProbabilityOnExecute = 0; Comparator byProbability() { ret (a, b) -> cmp(b.probability, a.probability); } new ThreadLocal threadProbability; persistable sclass Entry { double probability; Runnable action; *(double *probability, Runnable *action) {} run { action.run(); } toString { ret str(WithProbability(probability, action)); } } public void add aka at(double probability, Runnable action) { if (action == null) ret; if (probability < cutoffProbabilityOnAdd) ret; entries.add(new Entry(probability, action)); } public bool step() { ret stepFirstUnstepped(); } Entry nextSteppable() { Entry s = first(entries); if (s != null && s.probability < cutoffProbabilityOnExecute) null; ret s; } // returns false when done stepping bool stepFirstUnstepped() { Entry s = nextSteppable(), ret false if null; entries.remove(s); temp tempSetTL(threadProbability, s.probability); s.run(); true; } void reset { entries.clear(); } run { stepAll(this); } void run(int maxSteps) { stepMax(maxSteps, this); } void printStats() { Entry first = entries.first(), last = entries.last(); Entry next = nextSteppable(); print("ProbabilisticScheduler. " + nEntries(entries) + ", highest probability in queue: " + (first == null ? "-" : first.probability) + ", lowest probability in queue: " + (last == null ? "-" : last.probability) + ", cutoff probability: " + cutoffProbabilityOnAdd + "/" + cutoffProbabilityOnExecute + ", " + (next == null ? "done" : "next step: " + next.action)); } // Get probability of this thread's Runnable. // Or 1.0 when we are coming from "outside" (so you don't _have_ to // run your first step through the scheduler). double currentProbability aka current() { ret or(threadProbability!, 1.0); } IProbabilisticScheduler freeze() { double prob = currentProbability(); ret new IProbabilisticScheduler { public void at(double probability, Runnable action) { ProbabilisticScheduler.this.at(prob*probability, action); } }; } }