2

I've searched this along the way on the net but i haven't found an answer yet.. maybe someone of you guy knows this.

I'm developing a swing desktop like application; since I know that swing is not thread-safe (and if I call a method on a JComponent outside the EDT there is always the chance to get a deadlock with the EDT itself), I would like to have an exception thrown by the thread that is trying to call that method.. let me explain better:

suppose I have 2 threads: the EDT and a background worker ("BW"). If I call, for instance, JButton.setText(), or JButton.setIcon() within the BW there is a chance to get a deadlock with the EDT. Now I would like that when the BW calls JButton.setText() and exception is thrown to indicate that I'm doing very wrong..

I see that C# on VS2008 does this by default (I don't know if there is a way to disable this behaviour, but I think it is very useful to detect bad code). Is there a way to achieve a similar effect in java?

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
mimmoz81
  • 41
  • 5

3 Answers3

3

Take a look at this article which describes a RepaintManager which checks Swing threading violations. It will not catch all violations, but most of them.

You can easily adjust that class to throw Exceptions iso just printing a stack trace

Robin
  • 36,233
  • 5
  • 47
  • 99
1

Wrap each swing object you have in a Proxy, generated with reflection. Make that proxy compare the thread to the known good EDT thread. If doesn't match throw a RuntimeException.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Markus Mikkolainen
  • 3,397
  • 18
  • 21
1

Take a look at SwingUtilities.isEventDispatchThread. Calling this will return true if the call is made from within EDT, false otherwise.

It will do exactly what you want, the problem is you will probably have to make such calls in multiple places of your code; it's more work.

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69