Android HandlerThread: Handler post doesn't run Runnable sometimes

854 Views Asked by At

I am experimenting with HandlerThread on Android, and I can't seem to explain a strange behavior. Here is a class I am using to simply log a message through this unique thread.

public class HandlerLogger {
    MyHandler mHandler;
    HandlerThread myThread;

    private class MyHandler extends Handler {
        public MyHandler(Looper myLooper) { super(myLooper); }
    }

    public HandlerLogger() {
        myThread = new HandlerThread("my super thread");
        myThread.start();
        mHandler = new MyHandler(myThread.getLooper());
    }

    public void log(final String s) {
        mHandler.post(new Runnable() {
            @Override
            public void run() { Log.d("handler", s); }
        });
    }
}

And here is my usage of this class:

    HandlerLogger h = new HandlerLogger();
    for (int i = 0; i < 1000; i++) {
        h.log(String.valueOf(i));
    }

Now for the strange behavior: after running this many many times, sometimes the logs stop at about 7xx or 8xx (not a specific value), and most of the time it goes to 999, but it really seems as though all posts don't get run. Why is this? Can anyone give me an explanation?

Precision: I am using Genymotion emulator for these tests.

UPDATE: same behavior on real Device (Moto X 2012)

Thanks for any clue.

SOLVED: The reason why this was happening, is simply that android's logcat couldn't process handling so many entries, so it simply skips displaying them. The Handler's runnable does in fact run every time, and it can easily be checked this way:

    public class HandlerLogger {
    MyHandler mHandler;
    HandlerThread myThread;
    int hitsCounter;

    private class MyHandler extends Handler {
        public MyHandler(Looper myLooper) { super(myLooper); }
    }

    public HandlerLogger() {
        myThread = new HandlerThread("my super thread");
        myThread.start();
        mHandler = new MyHandler(myThread.getLooper());
    }

    public void log(final String s) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                hitsCounter++;
                Log.d("handler", s);
            }
        });
    }
}

just check the hitsCounter and you will notice it is in fact equal to 1000 as expected.

0

There are 0 best solutions below