Abhilash Gupta
Abhilash Gupta

Reputation: 63

AsyncTask maximum time limit allowed

What is the maximum time the Android ecosystem allows an AsyncTask task to run?

I have been asked this question many times in interviews, but I've never found a concrete answer.

Upvotes: 1

Views: 341

Answers (2)

Ryan M
Ryan M

Reputation: 20167

There isn't a fixed max time limit, at least from a technical perspective. An AsyncTask can run for an unlimited amount of time.

This can lead to a number of problems.

If you execute the AsyncTask by calling execute(), then they are run serially - that is, one after another, never running multiple at the same time. If you use execute() and your tasks runs for too long, you'll prevent other tasks run that way from executing until you're done If you execute it with executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR), it's slightly better, though it will still run a very limited number of tasks (varying based on various factors) in parallel.

In these situations, things could happen like a couple slow web requests (or entering a subway tunnel and the internet slowing down) could prevent all AsyncTasks in your app from running.

For this and other reasons, it is recommended, but not enforced, that AsyncTasks should not be used for anything other than relatively quick tasks, such as fast web requests or database reads.

Upvotes: 1

Mariusz Brona
Mariusz Brona

Reputation: 1609

Well, what I would say in the interview, is that the AsyncTask is deprecated in API 30:

https://developer.android.com/reference/android/os/AsyncTask

Then I would use some of the answers from this question: Android AsyncTask threads limits?

And in the end I would say something about Kotlin coroutines as the alternative:

https://developer.android.com/topic/libraries/architecture/coroutines

Upvotes: 0

Related Questions