Does an Android Looper thread use processing power?

775 views Asked by At

This question would probably also apply to the general world of Java threads...

I have a thread that I use like so (this is in the run method):

Looper.prepare();

Handler rHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        //ommited...
    }   
};

Looper.loop();

My question is whether the thread is using CPU while it's waiting for things to be pushed to the Handler? Or is it really "sleeping"?

Can having a couple of such threads bog down the system?

2

There are 2 answers

0
ZachM On BEST ANSWER

Underneath the hood, Looper is a facade at the Java layer for a native code Looper object (written in C++). The native code looper takes advantage of the Linux system call "epoll", which is an I/O event notification mechanism built for scalability (i.e. you can have tons of them with little performance impact - some memory impact though). This means when a Looper is hanging out in loop() and no messages are on the queue, nothing is actually being executed, thus it doesn't use processing power (just a little bit of memory). When a message is posted to the message queue on it, the thread will be "woken up" and process the message.

If you are interested in the code, see:

AOSP_ROOT/frameworks/native/libs/utils/Looper.cpp 
AOSP_ROOT/frameworks/base/core/java/android/os/Looper.java
AOSP_ROOT/frameworks/base/core/java/android/os/MessageQueue.java
AOSP_ROOT/frameworks/base/core/jni/android_os_MessageQueue.cpp
AOSP_ROOT/frameworks/base/native/android/looper.cpp
0
David Schwartz On

When the thread is waiting for a message, it is not ready to run. A thread that is not ready to run cannot use any CPU.