Reputation: 20536
I'm making an Android app and having trouble with occurences of RejectedExecutionException
(probably due to overuse of AsyncTask
). I'd like to get the default ThreadPoolExecutor
and read the getTaskCount()
and getCompletedTaskCount()
.
How does one get the instance of ThreadPoolExecutor
, without having created one manually?
Upvotes: 4
Views: 2901
Reputation: 6705
Right there in the doc for AsyncTask. There are two. They are called
AsyncTask.SERIAL_EXECUTOR
and
AsyncTask.THREAD_POOL_EXECUTOR
respectively.
Note that these two Executors both use exactly the same, multi-threaded backing Executor for execution. The Serial Executor is not single threaded! It simply has a dequeue in front of it, which forces serial execution of tasks.
Upvotes: 7
Reputation: 35232
You get RejectedExecutionException
because the waiting queue of the thread pool is full and you try to post another task. You should propably start here to refactor/rethink your code, because the queue size seems to be 10 plus the active thread which should be sufficent in most circumstances. Its very likely that some of your task don't finish or are long runngin task and block the others or that you wildly post threads ;)
Asynctask has 2 build-in thread pools:
SERIAL_EXECUTOR
- single thread pool THREAD_POOL_EXECUTOR
- concurrent execution up to 128 threads (5 core)In SDK > 11 SERIAL_EXECUTOR is default. So you maybe try THREAD_POOL_EXECUTOR
, but beware, that this can only be used in SDK => 11 because executeOnExecutor
was a newer method. This will fix your immediate problem, but you mabye should reconsider if you need that many threads. Or use other methods e.g. services if you have many long running tasks.
Alternatively if you want your own ThreadPool you can create one with Executors: e.g. Executors.newCachedThreadPool() (among other static constructors).
Upvotes: 0
Reputation: 2560
Android AsyncTask framework has two default executors: SerialExecutor
and ThreadPoolExecutor
. AsynkTask use different executor as default executor depends on platform.
Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution.
You can force select executor to execute task in execors you want using this function
You can pass AsycTask.SERIAL_EXECUTOR
or AsycTask.THREAD_POOL_EXECUTOR
to this function. And after it you can use it for your needs.
Upvotes: 0