Is there any way of killing a running AsyncTask immediately in libGDX?

The AsyncExecutor that submits it seems to just have one method (dispose()) that kills all the AsyncTasks that it handles after they've all managed to complete their runs.

Currently, to achieve what I want, I use a volatile boolean in the task class, loop on its value in the call() method of the same class, and then set it to false whenever I want to interrupt that specific task immediately.

I wonder though whether there's another, more direct, way of achieving this. Is there any other class or method responsible for this?


There appears to be nothing built-in to the AsyncTask API for this (most similar APIs have cancellation support, but libgdx's doesn't appear to).

You can implement it yourself. A simple approach is to use an appropriate thread synchronization primitive to control or act as signal to your asynchronous task that it should terminate stop working and early-out.

Properly guarded or marked up, a simple Boolean can suffice. Typically this means you will need to either check if the Boolean has been set to signal cancellation at the top of your tasks main loop and/or periodically throughout the execution of your task.

You can wrap this behavior up in your own utility class to avoid having to repeat it for every async operation you want to build, but even if you remove that boilerplate work you'll still have the issue where the cancellation is not immediate, it only happens at the level of granularity you perform the cancellation check. This is actually bad (because it means you could have a long wait between requesting a cancel and the actual cancel happening) and good (because it means you can make sure it's not possible to abort the async task while it's in the middle of transitioning some data between two valid states, and that way you ensure class invariants remain in place).

| improve this answer | |
  • \$\begingroup\$ Thank you for the explanation, I will assess the specific aspects of all my AsyncTasks and come up with a suitable implementation for disposing of them individually. \$\endgroup\$ – VictorB Jan 20 '14 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.