android


Android - how to check if ThreadPoolExecutor has reached the queue limit?


I use many AsyncTask classes in my app. I always start them using:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
asyncTask.execute();
}
Recently I got a RejectedExecutionException exception. I read about this and understand why this happens (exceeding the maximum number of tasks that thread pool executor can have in its queue).
But i didn't read anywhere about a way to check if thread pool executor has available slots so that I can avoid this. From what I tested the asyncTask.execute(); method does not have this limitation.
So I'm looking for something like this:
if(executorCanHandlerAnotherQueue()){
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
asyncTask.execute();
}
}
else{
asyncTask.execute();
}
Any ideas on how to implement this with backwards compatibility up to API 9?
AsyncTask uses thread pool pattern, so it just provide a default number of thread. If you call execute(), the task will wait for a worker thread free to do.
To execute in a real parallel, you can call executeOnExecutor(). But it also is limited (maximum number of tasks = thread pool size + task queue size).
You can create a custom Executor to increase number of thread or task queue like this:
public static final Executor CUSTOM_THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
For running executor() function for Android lower than HONEYCOMB, you can use
AsyncTaskCompat.executeParallel(task, params);
from support v4 library.
You can find more details in this answer
UPDATE:
For checking executor available before execute, you can write a small function like that:
boolean canExecutorAddAnotherQueue(ThreadPoolExecutor executor){
int active = executor.getActiveCount();
int corePoolSize = executor.getCorePoolSize();
int poolSize = executor.getPoolSize();
if (active < corePoolSize || active < poolSize) return true;
int queueSize = executor.getQueue().size();
if (queueSize < MAX_QUEUE_SIZE_YOU_DEFINED) return true;
return false;
}
But it maybe miss some cases that also accepted.
FINAL ANSWER:
So I found the best choice is using try catch:
try {
//execute asynctask
} catch (RejectedExecutionException e){
//Handle when has exception thrown
}
Or using custom handler:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
You can write your own handler for handling cases which the task is rejected, and not throw the RejectedExecutionException anymore.

Related Links

can we directly passe the mobile number to digits
Android: Simulating power button press using intent in terminal simulator
Firebase data not added to the right child
How to change navigation menu to back arrow?
Android - When to write to database, to prevent writing extensively
Execution failed for task ':app:transformClassesWithDexFor官方Debug'
Dagger 2 Scoped Activity Context Issue
How to save List in onDestroyView in Fragment?
upload data to server using json android
How to use AsyncTask?
Android actionbar won't show title or settings
Android - How to use Realm in FirebaseMessagingService class (non activity)
Display Name of Files In Progress Bar While Syncing
How change Searchable Spinner list background color in android?
How I can add users in Telegram channels using TLSharp?
How to launch my app by typing the name of the app?

Categories

HOME
google-app-engine
kentico
powerpoint
3d
error-handling
grafana
rendering
yandex
parameters
python-multithreading
lanczos
discrete-mathematics
accessibility
p2p
pattern-matching
project
pcl-crypto
windows-ce
tput
code-generation
onedrive-api
flash-player
flatpak
azure-iot-hub
red5
breadth-first-search
joptionpane
zxing
bulletphysics
boost-asio
volatile
mustache
code-snippets
jett
android-maps-extensions
installscript
engine.io
jpad
reactivekit
release
datacachefactory
branching-and-merging
photos
monkey-testing
plan-9
textsum
libgphoto2
opennms
spring-integration-sftp
globalize
aquamacs
wpas
polyline
slackware
vulcanize
ng-grid
nservicebus5
mediametadataretriever
ellucian-scribe
user-management
lazybones
ocra
kissfft
memset
superscrollorama
jquery-blockui
apache-commons-dbutils
gobject-introspection
role
expression-blend-4
user-tracking
mtu
easyb
hbm2java
qtabbar
dsl-tools
blind

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App