Skip to content Skip to sidebar Skip to footer

Android: Asynctask Or Normal Java Threads With Executorservice

My application uses a Service to do some background stuff. I am using additional threads in the service to do some computation. For this purpose I create two threads every 5 to 10

Solution 1:

If you look at the implementation of AsyncTask, you will see that it uses its own thread pool using "normal Java threads".

Is there a heavy overhead when i am using AsyncTasks, and is the ExecutorService faster in reusing the threads than Android in creating new AsyncTasks?

There should be no substantial difference between the two.

Solution 2:

I'm using Needle; an open-source, simple and powerful multithreading library for Android. With it you can say things like:

Needle.onMainThread().execute(newRunnable() {
    @Overridepublicvoidrun() {
        // e.g. change one of the views
    }
});

or

Needle.onBackgroundThread().execute(newUiRelatedTask<Integer>() {
    @OverrideprotectedIntegerdoWork() {
        int result = 1+2;
        return result;
    }

    @OverrideprotectedvoidthenDoUiRelatedWork(Integer result) {
        mSomeTextView.setText("result: " + result);
    }
});

Pros

  • very simple API
  • fixed thread pool size
  • customizable thread pool size
  • supports UI interaction ("do work and then use result on UI thread")
  • android 1.5+
  • behaves the same on all platform versions

Cons

  • extra library dependency

Check it out on GitHub: https://github.com/ZsoltSafrany/needle

Post a Comment for "Android: Asynctask Or Normal Java Threads With Executorservice"