Skip to content

Instantly share code, notes, and snippets.

@Groostav
Created December 11, 2015 19:16
Show Gist options
  • Save Groostav/cc3e9786bde5adec3b3f to your computer and use it in GitHub Desktop.
Save Groostav/cc3e9786bde5adec3b3f to your computer and use it in GitHub Desktop.
My first attempt at a re-usable requeing class
public class FXTimeKeeper {
private static final Logger log = Logger.getLogger(FXTimeKeeper.class.getCanonicalName());
public static final int SleepPeriod = getEnvInt(FXTimeKeeper.class, "SleepPeriod").orElse(50);
private final Queue<UpdateJob> jobs = new ConcurrentLinkedQueue<>();
private final SyncingUtilities syncingUtilities;
@Inject
public FXTimeKeeper(SyncingUtilities syncingUtilities) {
this.syncingUtilities = syncingUtilities;
ExceptionUtilities.assertIsSingleton(this);
syncingUtilities.asyncronously(
"OASIS FX time value formatter",
this::loopOnAndExecuteAvailableFormattingJobs,
Daemon
);
}
private void loopOnAndExecuteAvailableFormattingJobs() {
while (true) try {
jobs.removeIf(UpdateJob::isStale);
//remember that we're on an independent thread, so we can block as much as we like.
CountDownLatch jobsExhaustedSignal = new CountDownLatch(1);
dequeueExecuteAndRecurse(jobs.iterator(), jobsExhaustedSignal);
jobsExhaustedSignal.await();
syncingUtilities.sleepUnlessInterruptedFor(SleepPeriod);
}
catch (Exception exception) {
log.log(Level.WARNING, "error on FX time keeper", exception);
continue;
}
}
private void dequeueExecuteAndRecurse(Iterator<UpdateJob> remainingJobs, CountDownLatch jobsExhaustedSignal) {
if ( ! remainingJobs.hasNext()){
jobsExhaustedSignal.countDown();
return;
}
syncingUtilities.runLaterOnFXThread(() -> {
UpdateJob nextJob = remainingJobs.next();
try {
nextJob.run();
}
catch (Throwable error) {
jobs.remove(nextJob);
error = new RuntimeException(
"Caught exception while attempting to format value, removing the job! " +
"One time text field is likely stale!!",
error
);
Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), error);
}
dequeueExecuteAndRecurse(remainingJobs, jobsExhaustedSignal);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment