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

Android how to install apk file stored in assets folder
Why do i get a gap between checkbox and text?
Android 4.0 Ice Cream Sandwich FaceDetector does not return any Faces
Load fragment data only on time
How to prevent OutofMemoryError when building up a long list of string in android
Android Temperature Converter Not Functioning?
How do I transfer one of my Android Apps to another Android Developer account (not mine)
Android notification manager update percentage
Pressing on the notification removes alertDialog
bindService(): do I have to protect against onServiceConnected() never coming
Coming back from Camera Intent crashes Activity
Custom Component can't trigger listeners off
Android: Button.setOnClickListener makes error during runtime
TextToSpeech fall back to back end service when pre-recorded wav file missing
Using python regex for automating android jni methods signatures generation
Smart-phone app developing [closed]

Categories

HOME
algorithm
xml
microsoftgraph
scikit-learn
ggplot2
apache-jena
android-studio-2.2
alexa-skills-kit
powerpoint
requirements
vscode-extensions
alsa
web-hosting
gembox-spreadsheet
code-coverage
crystal-reports-2013
frontend
nstableheaderview
drop-down-menu
google-chrome-app
activecollab
line
xcodebuild
libc
plink
selectize.js
job-scheduling
microsoft-dynamics-nav
dreamweaver
production
charles
asciidoctor-pdf
gpio
jackson-modules
carrierwave
scatter3d
python-2.6
mustache
utorrent
record
jmockit
rselenium
clickjacking
video-capture
docfx
google-knowledge-graph
jpad
sim-card
spring-mvc-test
comparison-operators
tasm
android-checkbox
oim
snapchat
puredata
vaadin-elements
magento-2.0.7
gitlist
hammer.js
facebook-pixel
pair-programming
tinkerpop
azure-cli
modelsim
yii2-user
ngmaterial
flyout
cd-burning
ziparchive
centrifuge
dup
jclouds
angular-ui-typeahead
gcloud-ruby
thread-sleep
pushbots
qbxml
contentcontrol
highland.js
dllimport
evolus-pencil
sony-lifelog-api
atoi
sql-server-data-tools
entity-framework-4.3
android-broadcast
code-documentation
openbabel
boost-program-options
appserver
encryption-asymmetric
gnumeric
vbe
high-resolution
hibernate-entitymanager
css-reset
nokia-s40
failing-tests
ilasm
fitbounds
relative
filemerge
google-floodlight
w3c-geolocation
timthumb
tmx
mtu
maven-1
echo3
feasibility
lobo-cobra
contentpresenter
mathematical-typesetting

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