Is there a robust way to detect if Thread.currentThread() is the Android system GUI-thread in an application? I would like to put some asserts in my model code that asserts that only one thread (eg the gui-thread) accesses my state, to assure that no kind of synchronization is neccesary.
My application is working, but, it has several authors and is becomming rather big and complex. What I want to do is to add an extra safety net, an assert that catches the misstake if somebody is calling a method that is designed to only be called from the GUI-thread from another thread.
ParDroid
2010-05-17 12:30:08
A:
You could use Thread.toString()
. It returns a string which can be used to uniquely identify each thread. Use it to compare your main gui's thread. Get the main GUI thread from OnCreate with a call like this: Thread.currentThread().toString()
Brad Hein
2010-05-17 13:07:01
Don't use the name, several threads can have the same name. You should rely on the thread's identity instead. Just keep a reference to the Thread.
Romain Guy
2010-05-17 16:08:24
Interesting, thanks for pointing that out Romain. Can you suggest an example where two threads may have the same .toString()?
Brad Hein
2010-05-17 16:54:28
Thanks Romain for the idea of retaining a reference to the thread. I guess I can make a static MyAsserter.assertAlwaysSameThread() that keeps a thread reference and checks that its always the same thread that calls it. And also make sure to call it in onCreate aswell.
ParDroid
2010-05-17 18:09:51