Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if the calling thread is the SWT UI thread - determine the calling thread

Tags:

java

swt

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

like image 429
Mircea Avatar asked Aug 14 '12 11:08

Mircea


1 Answers

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);
}
like image 138
Edward Thomson Avatar answered Nov 10 '22 17:11

Edward Thomson