My strategy for threading issues in a Swing Java app is to divide methods in three types:
I think this is a valid approach for GUI apps, where there are usually only two threads. Cutting up the problem really helps to reduce the "surface area" for race conditions. The caveat of course is that you never accidentally call a method from the wrong thread.
My question is about testing:
Are there testing tools that can help me check that a method is called from the right thread? I know about SwingUtilities.isEventDispatchThread()
, but I'm really looking for something using Java annotations or aspect-oriented programming so that I don't have to insert the same boilerplate code in each and every method of the program.
To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.
Testing a multithreaded application is more difficult than testing a single-threaded application because defects are often timing-related and more difficult to reproduce.
You want to achieve mutual exclusion with doSomeTimeConsumingAction , so that only one thread at a time can be running the doSomeTimeConsumingAction method of an object at a time. Alternatively, use a synchronized block in the threads themselves, which acquires a lock on the object.
To test multi-thread functionality, let the multiple instances of the application or program to be tested be active at the same time. Run the multi-thread program on different hardware. Thread testing is a form of session testing for which sessions are formed of threads.
Here is a blog entry with a few solutions for checking EDT violations. One is a custom repaint manager and there is also an AspectJ solution. I have used the repaint manager in the past and found it quite useful.
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