I have this module that's being used in multiple parts of the application COMM (on the SWT Ui side , on the backend etc). This module has a method sendMessage in which I want to add a routine to determine if the calling thread (just in case of using this in the UI) is the SWT UI thread. And warn the programmer that he is trying to do a time consuming operation from the UI thread ... which is bad :)
I want to do this ofcourse by not adding any dependencies on the UI module (from COMM).
How can I determine if the calling thread is the SWT UI thread ?
Thanks, Mircea
You can call Display.getThread()
to get the current UI thread for your application.
If you don't want to take dependencies on SWT UI, then you'll have to use reflection. For example:
public static boolean isUIThread()
{
Object uiThread = null;
try
{
Class displayClass = Class.forName("org.eclipse.swt.widgets.Display");
Method getDefaultMethod = displayClass.getDeclaredMethod("getDefault", new Class[] { });
Object display = getDefaultMethod.invoke(null, new Object[] { });
Method getThreadMethod = displayClass.getDeclaredMethod("getThread", new Class[] { });
uiThread = getThreadMethod.invoke(display, new Object[] { });
}
catch(Exception e)
{
log.warn("Could not determine UI thread using reflection", e);
}
return (Thread.currentThread() == uiThread);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With