I have context, which may be used to produce prognosis. Algorithm to make prognosis based on context isn't part of my question. But it is time-expensive, so I moved it out from main thread. In any time context may be changed. When this happens app should restart prognosis producing with new input. Prognosis related to old context will became invalid, so its calculation should be interupted.
For now I use code:
public class BackgroundTasksManager {
public static final BackgroundTasksManager shared = new BackgroundTasksManager();
private ExecutorService conceptResultsExecutor = null;
private BackgroundTasksManager() { }
public void startConceptResultsCalculation(ConceptResultsCalculationInput input,
Consumer<ConceptResultsCalculationOutput> callback) {
ThreadGroup callbackGroup = Thread.currentThread().getThreadGroup();
if (conceptResultsExecutor != null)
conceptResultsExecutor.shutdownNow();
conceptResultsExecutor = Executors.newSingleThreadExecutor();
conceptResultsExecutor.submit(() -> {
ConceptResultsCalculationOutput output = ConceptResultsCombinator.possbileResults(input);
Thread callbackThread = new Thread(callbackGroup, () -> callback.accept(output));
callbackThread.start();
});
}
So, when I need to start prognosis calculation, I shut down old Executor and create new one. This solution works, but is it valid, or hide some dangerous nuances?