Consider a user interface that accepts configuration settings for a service that takes a long time to initialize (for example, the parameters for a JDBC connection). We want our user interface to remain responsive while the service initialization occurs. If the user makes additional changes, the initialization should be cancelled and restarted using the new parameters.
Because parameters are incorporated in the configuration as the user types each character, it’s possible that a number of initialization requests could be created in a row. Only the last one should be executed.
We have code that we’ve put together that achieves this result, but it seems like this behavior is a very good candidate for implementation as an ExecutorService. Before we refactor everything into an ExecutorService, I figured I would ask if there are similar implementations already out in the world.
To be more specific:
The ExecutorService would have one worker thread. As soon as a new task is submitted, the current task is cancelled (and the worker interrupted). The new task is then captured for the next execution. If another task is submitted, the current task is cancelled again, and the “next execution” task is set to this new task. When the worker thread finally picks up the next task for execution, it will always be the last task submitted – all other tasks are either cancelled or discarded.
Does anyone have an implementation like that they’d be willing to share? Or is there maybe a standard library that covers this type of behavior? It’s not hard to implement, but getting the thread safety nailed down can be tricky, so I’d rather use proven code if we can.
Here’s what I eventually came up with – I’m interested in any comments: