I have a single threaded executor service for fetching some data over the network.

As the user is typing in a search box I am enqueuing possible network tasks. What I want is to cancel all previous requests and only enqueue and immediately run the latest one.

My current approach is to override execute() and submit() methods and clear the queue before calling super.

Any thoughts on this?

有帮助吗?

解决方案

Don't get it, why don't you save the Future returned on posting a callable to the service, and then cancel() the future if you don't want it to be executed.

e.g.

Future f1 = service.submit(some_task);

// later

f1.cancel(true); // will interrupt if running...

Cleaner IMO...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top