HandlerThread should i override run()? - android

I'm trying to use the HandlerThread class to manage thread in my application. The following code is working great :
public class ThreadA extends HandlerThread
{
private void foo()
{
//do something
}
private void bar()
{
//Do something else
}
#Override
public boolean handleMessage(Message msg) {
switch(msg.what)
{
case 1:
{
this.foo();
break;
}
case 2:
{
this.bar();
break;
}
}
return false;
}
#Override
protected void onLooperPrepared()
{
super.onLooperPrepared();
synchronized (this) {
this.AHandler = new Handler(getLooper(),this);
notifyAll();
}
}
}
1- Should i override the run() method ? In a "classic" thread most of the code is located in the run method.
2- Lets imagine i need my foo() method to be a infinite process (getting a video streaming for example).
What's the best solution ?
Overriding run with my foo() code ?
Simply adding a sleep(xxx) in foo() :
private void foo()
{
//do something
sleep(100);
foo();
}
-Using a delayed message like :
private void foo()
{
//do something
handler.sendEmptyMessageDelayed(1,100);
}
PS : Asynctask will not cover my need , so do not bother to tell me to use it.
Thanks

I think you didn't get the idea of HandlerThread. HandlerThread is designed to implement thread that handles messages. What this means is that it uses Looper.loop() in its run() method (and that's why you shouldn't override it). This in turn means that you don't need to sleep in onHandleMessage() in order to prevent thread from exiting, as Looper.loop() already takes care of this.
To summarize:
No, do not override run().
You don't need to do anything to keep thread alive.
If you want to learn/undestand more about HandlerThread, read about Looper and Handler classes.

You shouldn't override the run method in the HandlerThread since that is where the core functionality of the class actually occurs. Based on what you are showing, I also see no reason to do so.
If your task itself is infinite, there isn't anything preventing you from having it execute that way. The only reason you might want to use handler.sendEmptyMessageDelayed is if you plan to have other tasks that you want run queued on the HandlerThread while foo() is executing. The other approach you recommended will prevent the HandlerThread from handling any other message. That being said, I suspect there is a better way to make your task infinite.
Finally, you should remember to stop your infinite task and call HandlerThread.getLooper().quit() to make sure your HandlerThread stops nicely.

Related

Espresso and postDelayed

I have an activity which is using a postDelayed call:
public class SplashActivity extends Activity {
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
handler.postDelayed(new Runnable() {
public void run() { finish(); }
}, 3000L);
}
}
This runs at app startup, and i need to navigate it and my login screen. However, the UIController's loopMainThreadUntilIdle doesn't seem to take the underlying MessageQueue in the handler into account. As such, this action finishes immediately while there is still messages in the queue.
onView(withId(R.id.splash_screen)).perform(new ViewAction() {
#Override
public Matcher<View> getConstraints() {
return isAssignableFrom(View.class);
}
#Override
public String getDescription() {
return "";
}
#Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
}
});
I've been unable to figure out how to block until the queue is drained. Android itself is preventing me from doing a lot of things i would have tried (like extending Handler and overriding the postDelayed method, etc...)
Anyone have any suggestions on how to handle postDelayed?
I'd rather avoid uiController.loopMainThreadForAtLeast, which seems hacky (like a Thread.sleep would)
When Espresso waits, it actually does take in account MessageQueue, but in a different way from what you think. To be idle, the queue must either be empty, or have tasks to be run in more than 15 milliseconds from now.
You can check the code yourself, especially the method loopUntil() in UiControllerImpl.java and the file QueueInterrogator.java. In the latter file you will also find the logic of how Espresso checks the MessageQueue (method determineQueueState()).
Now, how to solve your problem? There are many ways:
Use AsyncTask instead of Handler, sleeping on the background thread and executing actions onPostExecute(). This does the trick because Espresso will wait for AsyncTask to finish, but you might not like the overhead of another thread.
Sleep in your test code, but you don't like that approach already.
Write your custom IdlingResource: this is a general mechanism to let Espresso know when something is idle so that it can run actions and assertions. For this approach you could:
Use the class CountingIdlingResource that comes with Espresso
Call increment() when you post your runnable and decrement() inside the runnable after your logic has run
Register your IdlingResource in the test setup and unregister it in the tear down
See also: docs and sample, another sample
As far as I know there is no wait for activity to finish method in espresso. You could implement your own version of waitForCondition, something robotium has. That way you'll only wait for as long as is needed and you can detect issues with your activity not finishing.
You'd basically poll your condition every x ms, something like.
while (!conditionIsMet() && currentTime < timeOut){
sleep(100);
}
boolean conditionIsMet() {
return "espresso check for if your splash view exists";
}

How to correctly use a Workerthread?

I've been writing android apps for some months now, and I'm at the point where I'm building an actual needed app.
As I want that to work nice and fast, I made a Workerthread to do all kinds of tasks in the background while the UI can...build up and work and stuff.
It's based on the Android Studio Drawer app blueprint.
In Main.onCreate I got my operator=new Operator(), which extends Thread.
Now, when loading a new Fragment, it sometimes calls MainActivity.operator.someMethod() (I made operator static so I can use it from anywhere), and after some time I realized, the only tasks actually running in background are those in the operators run() method and an Asynctask my login Fragment runs. Everything else the UI waits for to complete and therefore gets executed by the UI thread.
So I thought: no problem! My operator gets a handler which is built in run(), and I change those tasks:
public void run() {
Looper.prepare(); //Android crashed and said I had to call this
OpHandler = new Handler();
LoadLoginData();
[...Load up some Arrays with hardcoded stuff and compute for later use...]
}
public void LoadLoginData() {
OpHandler.post(LoadLoginDataRunnable);
}
private Runnable LoadLoginDataRunnable = new Runnable() {
#Override
public void run() {
if(sharedPreferences==null)
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(context);
sessionID=sharedPreferences.getString("sessionID", null);
if(sessionID!=null) {
postenID = sharedPreferences.getString("postenID", PID_STANDARD);
postenName = sharedPreferences.getString("postenName", PID_STANDARD);
context.QuickToast(sessionID, postenName, postenID);
}
}
};
context is my MainActivity, I gave the operator a reference so I could send Toasts for Debugging.
But now, the Runnables seem to not run or complete, any Log.e or Log.d stuff doesn't arrive in the console.
After some googeling and stackoverflowing, everyone is just always explaining what the difference is between Handlers, Asynctask, and Threads. And the multitask examples always only show something like new Thread(new Runnable{run(task1)}).start times 3 with different tasks.
And so became my big question:
How to correctly, over a longer time (~lifecycle of the MainActivity), with different tasks, use a background thread?
Edit: to clarify, I would also like a direct solution to my special problem.
Edit 2: after reading nikis comment (thank you), the simple answer seems to be "use HandlerThread instead of thread". Will try that as soon as I get home.
Trying a HandlerThread now. It seems my OpHandler, initialized in run(), gets destroyed or something after run() has finished, not sure whats up here (this is btw another mystery of the kind I hoped would get answered here). I get a NullpointerException as soon as I try to use it after run() has finished.
Make your worker thread own a queue of tasks. In the run() method, just pop a task from the queue and execute it. If the queue is empty, wait for it to fill.
class Operator extends Thread
{
private Deque<Runnable> tasks;
private boolean hasToStop=false;
void run()
{
boolean stop=false;
while(!stop)
{
sychronized(this)
{
stop=hasToStop;
}
Runnable task=null;
synchronized(tasks)
{
if(!tasks.isEmpty())
task=tasks.poll();
}
if(task!=null)
task.run();
}
}
void addTask(Runnable task)
{
synchronized(tasks)
{
tasks.add(task);
}
}
public synchronized void stop()
{
hasToStop=true;
}
}

Java Android Native thread issues

I have one thread that does lot of time consuming tasks. The tasks are being done in the native part in c++. I would like to cancel the operation that is being done in the native, the code for that is place. I can reset everything.
mWorker = new WorkerThread("Worker thread");
mWorker.start();
//From Main thread:- Interrupting
mWorker.interrupt();
if(mWorker.isInterrupted()) {
Log.i(MOD_TAG, "Worker thread is interupptedd!!! ");
}
//Worker thread
public class WorkerThread extends Thread implements Runnable{
public void run() {
while(!Thread.currentThread().isInterrupted()) {
Looper.prepare();
mHandler = new WorkerHandler();
Looper.loop();
}
class WorkerHandler extends Handler {
#Override public void handleMessage(Message msg) {
try {
switch(msg.what) {
//do something native code
}
}
catch (Exception e) {}
}
}
}
}
Even if the workerthread is interrupted I cannot send any message to the worker thread while the worker thread is doing processing. Can I do something to post a message to workerthread or do something else that could let me call a native method within the same thread.
In your example, I don't understand what that Handler is doing inside the Thread. Once you call loop() within the run, that call will block until the looper is stopped via quit() or quitSafely(). The call is basically just a loop which reaps a queue for messages. Your check for interrupt will never happen.
I would recommend something like this. If you want your code to be managed by a handler you would do something like:
HandlerThread handlerThread = new HandlerThread("NativeHandler");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper()) {
public void handleMessage(Message msg) {
someObject.callNativeLongRunningFuction();
}
};
However interrupt still won't do anything because the looper only handles one message at a time. So if it is stuck handling callNativeLongRunningFunction(), that is not going to help you really either. If you want to have interrupt stop the ongoing execution of the jni call, the I don't think this approach will work at all with the given information. Interrupt in java only sets a flag and when there is a call to wait(), it will throw an exception when that flag is checked and also set. But for a jni call there isn't a call to wait(), the java stack is sort of blocked but it is not in the middle of a wait() either. So unless you check interrupted within the native runtime, that function will continue to run. Overall I am guessing this probably would not be what you really want.
If that is so, I would recommend something like this instead.
public class NativeThreadTask {
public native void start();
public native boolean isRunning();
public native boolean cancel();
}
Inside the native implementation of that class, you would then use a pThread to call your native long running function. Start and Cancel would manipulate that pThread which would run the expensive function in a separate thread. Using pthread_cancel you can interrupt that pthread instance too. This moves the long operation off your thread and out of your runtime, while still allowing you to control when the pthread interrupt mechanism is invoked but over the jni bridge. If you don't even want to interrupt and if the long running native call is iterating over a large amount of data, then it might be worthwhile to have cancel() simply change bool that is evaluated within each iteration of the native function's loop.
So with the given example you could probably do something like this.
NativeThread nativeThread = new NativeThread();
Handler handler = new Handler() {
public void handleMessage(Message message) {
NativeThread nativeThread = (NativeThread)message.obj;
switch(message.what) {
case 0:
if (!nativeThread.isRunning()) {
nativeThread.start();
}
break;
case 1:
if (nativeThread.isRunning()) {
nativeThread.cancel();
}
break;
default:
}
}
};

How to implement a more flexible AsyncTask?

while it is very convenient to use, from my understanding, AsyncTask has two important limitations:
doInBackground of any instances will share the same worker
thread, i.e. one long running AsyncTasks can block all others.
execute, onPostExecute and other "synchronizing" methods must/will always be executed on the UI-thread, i.e. not on the Thread, which wants to start the task.
I ran into trouble, when I tried to reuse some existing AsyncTasks in a background IntentService that are responsible for the client-server communication of my app. The tasks of the service would fight over time in the worker thread with those of the UI activities. Also they would force the service to fall back onto the UI-thread, although that service should perform its work quietly in the background.
How would I go about removing/circumventing these limitations? I basically want to achieve:
A framework that closely resembles AsyncTask (because I need to migrate a lot of critical code there).
Each instance of such a task should run its doInBackground on its own thread instead of a single worker thread for all instances.
Edit: Thx to VinceFR for pointing out this can be achieved by simply calling executeOnExecutor instead of execute.
The callbacks like onPostExecute should be called on the same thread that started the task by calling execute, which should not need to be the UI-thread.
I figure, I'm not the first person to require something like this. Therefore I wonder: Is there already some third-party library that can be recommended to accomplish this? If not, what would be a way to implement this?
Thanks in advance!
The solution looks like this:
All classes that spawn AsyncTasks that might interfere with each other get their own Executor like this one (make that elaborate as you like using thread pools etc.):
private Executor serviceExecutor = new Executor() {
public void execute(Runnable command) {
new Thread(command).start();
}
};
As pointed out by VinceFR you can run an AsyncTask on a given Executor by calling it like this (where payload are the parameters that you would regularly pass to a task):
task.executeOnExecutor(serviceExecutor, payload);
However, this breaks backwards-compatibility to Gingerbread and earlier. Also, if you want to support Honeycomb, you need to make sure, this call happens on the UI thread. Jelly Bean will take care of this automatically.
Now the trickier part: Keeping the service running on its own thread. As many things in Android this seems harder than it needs to be (or maybe I'm lacking some information here). You can't use an IntentService, because that will shut down automatically the first time an AsyncTask takes over and let's the onHandleIntent callback complete.
You need to setup your own thread and event loop on the service:
public class AsyncService extends Service {
private static final String TAG = AsyncService.class.getSimpleName();
private class LooperThread extends Thread {
public Handler threadHandler = null;
public void run() {
Looper.prepare();
this.threadHandler = new Handler();
Looper.loop();
}
}
private LooperThread serviceThread = null;
private Handler serviceThreadHandler = null;
#Override
// This happens on the UI thread
public void onCreate() {
super.onCreate();
}
#Override
// This happens on the UI thread
public int onStartCommand(Intent intent, int flags, int startId) {
this.serviceThread = new LooperThread();
this.serviceThread.start();
while(this.serviceThread.threadHandler == null) {
Log.d(TAG, "Waiting for service thread to start...");
}
this.serviceThreadHandler = this.serviceThread.threadHandler;
this.serviceThreadHandler.post(new Runnable() {
#Override
public void run() {
doTheFirstThingOnTheServiceThread();
}
});
return Service.START_STICKY;
}
// doTheFirstThingOnTheServiceThread
}
No you need to make sure that each time an AsyncTask returns to the UI thread, you end up in your service thread instead:
// This happens on the serviceThread
private void doTheFirstThingOnTheServiceThread() {
// do some stuff
// here we can reuse a class that performs some work on an AsyncTask
ExistingClassWithAsyncOperation someUsefullObject = new ExistingClassWithAsyncOperation();
// the existing class performs some work on an AsyncTask and reports back via an observer interface
someUsefullObject.setOnOperationCompleteListener(new OnOperationCompleteListener() {
#Override
// This happens on the UI thread (due to an ``AsyncTask`` in someUsefullObject ending)
public void onOperationComplete() {
serviceThreadHandler.post(new Runnable() {
#Override
public void run() {
doTheSecondThingOnTheServiceThread();
}
});
}
}
someUsefulObject.performOperation();
}
// This happens on the serviceThread
private void doTheSecondThingOnTheServiceThread() {
// continue working on the serviceThread
}
So, this works for me. I'd be delighted to see a simpler solution for this. Note that the solution requires the service to know that is will be called back by the ExistingClassWithAsyncOperation on the UI thread. I don't particularly like this dependency, but don't know how to do better right now. However, I don't have to rewrite a lot of existing classes that perform asynchronous operations using AsyncTask.

Using Synchronized in While Loops

I've found the following code does not work because the while loop steals the lock indefinitely:
public void run()
{
while(true)
{
synchronized(run)
{
if (!run) break;
[code]
}
}
}
public void stopRunning()
{
synchronized(run)
{
run = false;
}
}
My goal is to ensure that I don't return from a stopRunning() command until I know that my run() function is no longer actually running. I'm trying to prevent the run function from continuing to reference other things that I'm in the process of destroying. My first thought then is to add a line of code such as Thread.sleep(100) prior to synchronized(run) in order to ensure that it releases the lock. Is this the recommended practice or am I overlooking something [stupid/obvious]?
Thanks!
If you just need stopRunning() to block until run() finishes doing stuff, you could just use a CountDownLatch set to 1. Call it stoppedSignal or something, and in run() you can call stoppedSignal.countDown() when it is finished. In stopRunning you can then set your condition for run() to finish and then call stoppedSignal.await(). It won't proceed until run() "releases" the latch by counting down. This is just one way to do it that would be a bit neater. All the synchronized block stuff that be got rid of.
Beware of the "synchronized" keyword - it's a very blunt and old tool. There are some wonderful things in the concurrency package that fulfil specific purposes much more neatly. "Concurrency In Practice" is a fantastic book on it.
Would something like this suffice?
public void run()
{
while(run)
{
[code]
}
onRunStopped();
}
public void stopRunning()
{
run = false;
}
public void onRunStopped()
{
// Cleanup
}
while synchronized(run) will lock run, you can use run.wait() to freeze the thread run() is executed in.
in another thread, use run.notify() or run.notifyAll() to get run() to continue.
synchronized is used to sync between threads. use it only if there is a potential race condition between 2 or more of them.
Ensure the 'run' object is the same from both point in the code.
The while loop should be synchronizing to the same object as the stopRunning() method.
The while loop is not hogging the lock, it is more likely that the two pieces of code could be referencing a different object. But I cannot tell because the run object is not shown in the code.
There are probably more elegant solutions, but I believe you could solve it with the changes bellow:
private boolean lock;
public void run()
{
while(true)
{
synchronized(lock)
{
if (!run) break;
[code]
}
}
}
public void stopRunning()
{
run = false;
synchronized(lock){ }
}

Categories

Resources