Find out if the calling thread is a UT SWT thread - identify the calling thread

I have this module, which is used in many parts of the COMM application (on the SWT Ui side, on the backend, etc.). This module has a sendMessage method in which I want to add a subroutine to determine if the calling thread (just when using this in the user interface) is a UT SWT thread. And warn the programmer that he is trying to execute a lot of time from the user interface thread ... which is bad :)

I want to do this without adding any dependencies on the user interface module (on COMM).

How to determine if the calling thread is a UT SWT thread?

Thanks Mircea

+6
source share
2 answers

You can call Display.getThread() to get the current UI thread for your application.

If you do not want to accept dependencies on the SWT interface, you will have to use reflection. For instance:

 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); } 
+9
source

I believe that this code at runtime will determine if the current thread is a user interface thread in SWT. This is basically the same answer as before, without using reflection.

if (Thread.currentThread () == Display.getDefault (). getThread ())

0
source

Source: https://habr.com/ru/post/922825/


All Articles