My program threw a NullPointerException the other day when I tried to use a handler created in another thread to send a message to this thread. A handler created by another thread has not yet been created or is not yet visible to the calling thread, even though the calling thread has already called the start in another thread. This is very rare. Almost every test run does not receive an exception.
I was wondering how best to avoid this problem, with minimal complexity and a penalty for performance. The program is a game and is very sensitive to performance, especially after its launch. Therefore, I try to avoid using synchronization after installation, for example, and would prefer to avoid turning on a variable at any time.
Background:
On Android, the Handler class can be used to "trigger an action that must be executed on a thread other than your own." The documentation is here:
http://developer.android.com/intl/de/reference/android/os/Handler.html
A handler must be created in the stream where it will be used. Therefore, creating it in a thread constructor that is started by the thread creating this thread is not an option.
When the handler is for a thread other than the user interface thread, the Looper class should also be used:
http://developer.android.com/intl/de/reference/android/os/Looper.html
The documentation provides an example of using two classes for this purpose:
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) {
My very ugly workaround currently looks like this:
public class LooperThread extends Thread { public volatile Handler mHandler; public final ArrayBlockingQueue<Object> setupComplete = new ArrayBlockingQueue<Object>(1); public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) {
With the code in thread creation, it looks like this:
LooperThread otherThread = new LooperThread(); otherThread.start(); otherThread.waitForSetupComplete(); otherThread.mHandler.sendEmptyMessage(0);
Are there any better solutions? Thanks.
java android null multithreading
Lance nanek
source share