I hava some code like this:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
I want to know which thread the “mHandler” belong to?
Add: Is it different if I declare(or instance it) in different thread.
It doesn’t belong to any thread. It is public so any thread can access it and modify. That being said it is crucial to make it thread safe (your code isn’t – the variable isn’t
volatile).The bottom line is – every object created using
newoperator is placed on the heap which is shared among all the threads. Other threads can access the object reference e.g. if it is not encapsulated like in your example or exposed on purpose.Technically speaking – in Java any object does not belong to any other – all references to a given object are equal. And when the last reference to the object (huge oversimplification) are gone, it is garbage collected. So one can say: the last reference owns the object.