Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect synchronization violations with Java

I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing).

That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have some assertion that would inform me (log or something) if some method(s) of it was called from multiple threads.

I'm longing for something similar that could be made for AWT dispatch thread with the following:

public static void checkDispatchThread() {
    if(!SwingUtilities.isEventDispatchThread()) {
        throw new RuntimeException("GUI change made outside AWT dispatch thread");
    }
}

I'd only want something more general. The problem description isn't so clear but I hope somebody has some good approaches =)

like image 939
Touko Avatar asked Nov 18 '08 14:11

Touko


4 Answers

You are looking for the holy grail, I think. AFAIK it doesn't exist, and Java is not a language that allows such an approach to be easily created.

"Java Concurrency in Practice" has a section on testing for threading problems. It draws special attention to how hard it is to do.

like image 101
Steve McLeod Avatar answered Oct 20 '22 03:10

Steve McLeod


When an issue arises over threads in Java it is usually related to deadlock detection, more than just monitoring what Threads are accessing a synchronized section at the same time. JMX extension, added to JRE since 1.5, can help you detect those deadlocks. In fact we use JMX inside our own software to automatically detect deadlocks an trace where it was found.

Here is an example about how to use it.

like image 37
Fernando Miguélez Avatar answered Oct 20 '22 04:10

Fernando Miguélez


IntelliJ IDEA has a lot of useful concurrency inspections. For example, it warns you when you are accessing the same object from both synchronised and unsynchronised contexts, when you are synchronising on non-final objects and more.

Likewise, FindBugs has many similar checks.

like image 21
Dan Dyer Avatar answered Oct 20 '22 04:10

Dan Dyer


As well as @Fernando's mention of thread deadlocking, another problem with multiple threads is concurrent modifications and the problems it can cause.

One thing that Java does internally is that a collection class keeps a count of how many times it's been updated. And then an iterator checks that value on every .next() against what it was when the interator was created to see if the collection has been updated while you were iterating. I think that principle could be used more generally.

like image 1
Paul Tomblin Avatar answered Oct 20 '22 03:10

Paul Tomblin