File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Unit testing synchronized code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Unit testing synchronized code" Watch "Unit testing synchronized code" New topic

Unit testing synchronized code

Zico Gupta

Joined: Apr 27, 2011
Posts: 10
Hello Javier,
Is it possible to unit test some synchronized method/block of synchronized code to ensure that the method/code itself is synchronized? What would be the assertion statement? Also, is there any guaranty that this particular test will pass in different jvm and java version?

Thanks & Regards,
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
Hmmm... there's the method Thread.holdsLock(Object), which sort of does what you ask. Almost. But since it only operates on the current thread, not on an arbitrary Thread object, I have a hard time imagining a way to use it effectively as part of a unit test.

Still, if you need to verify that a particular block of code is synchronized, why not just make it synchronized? That way you're sure. Of the many complicated things to think about in concurrency, this one doesn't seem too tough. Knowing whether you should sync a particular bit of code, and on what monitor - that's the hard part. Ensuring that is is synchronized on that monitor - that's easy.
Javier Fernandez Gonzalez

Joined: Dec 10, 2012
Posts: 20
Hello Zico and Mike

Testing a concurrent application is a complex task. As the order of execution of the tasks are not guarantee, you can't simulate all the possible options. As Mike said, if you make a block of code synchronized, you have the guarantee that only one thread will execute that portion of code. If you want to test that more than one thread are synchronized between them and they don't generate inconsistency results, you can take a look to the MultithreadedTC library. It includes an internal metronome to control the order of execution of tasks, so you can provoke a problematic situation to check if your code behaves as expected. The book includes a recipe in the chapter 8, Testing Concurrent Applications, that explains how to use that library.

If you need more info, please let me know.

Author of Java 7 Concurrency Cookbook
I agree. Here's the link:
subject: Unit testing synchronized code
It's not a secret anymore!