My doubt is regarding how to run a piece of code within an API in my service, on another thread.
I have an API func in my service. Only a part of this API's code, which is independent (2-3 LOC), I want to move it to separate thread, as these take up siginificant time, and as these lines of code have no impact on UI thread as of now. This is what I did.
ORIGINAL CODE:
func(){
subA();
subB();
subC();
}
MODIFIED CODE:
Thread mThread = null;
func(){
subA();
if(mThread == null){
mThread = new Thread(){
public void run(){
subB();
subC();
}
}
}
mThread.start();
}
On running this code, I am getting an exception for "thread already started".
I did read on SO about this, that an already started thread cannot be re-started again. I need to create a new thread again and start that. But I do not want to create a new thread object everytime, as that will lead to performance issues on UI thread. Is there any other way this can be handled.
I discovered a couple of other ways to acheive this in android, like Handler, HandlerThread, AsyncTask, etc. But I am not able to settle my mind on which is the best to use here (I do not want to create new objects everytime (of thread/asynctask/handler/handlerthread
), just wan to create thread object once and re-use it everytime).
If anybody has worked on this area before, please help !
On further looking into thread part, I managed to find that using ThreadHandler is simpler than using a thread + a looper (as a ThreadHandler has a looper attached to it by default, and manages it well). So, this is the code I am looking towards for now.
HandlerThread mThread = null;
Handler mHandler = null;
func(){
subA();
if(mThread == null){
mThread = new HandlerThread("mThread");
mThread.start();
mHandler = new Handler(mThread.getLooper());
}
mHandler.post(new Runnable(){
public void run(){
subB();
subC();
}});
}
But I find one issue with this code, I still need to create a new object of a runnable on each call to func(). Need to find out how I can avoid this.
Move the mThread.start();
inside the if(mThread == null)
block. You're starting the same thread unconditionally on subsequent calls to the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With