Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: testing thread access to "not thread-safe" methods

My strategy for threading issues in a Swing Java app is to divide methods in three types:

  1. methods that should be accessed by the GUI thread. These methods should never block and may call swing methods. Not thread-safe.
  2. methods that should be accessed by non-GUI threads. Basically this goes for all (potentially) blocking operations such as disk, database and network access. They should never call swing methods. Not thread-safe.
  3. methods that could be accessed by both. These methods have to be thread-safe (e.g. synchronized)

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.

like image 811
amarillion Avatar asked Sep 04 '09 10:09

amarillion


People also ask

How can you tell if something is thread safe?

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.

Why is testing multithreaded concurrent code so difficult?

Testing a multithreaded application is more difficult than testing a single-threaded application because defects are often timing-related and more difficult to reproduce.

How do you restrict access to an object to one thread at a time?

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.

How do you test threads?

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.


1 Answers

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.

like image 125
Mark Avatar answered Sep 19 '22 15:09

Mark