• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unit testing synchronized code

 
Zico Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
Zico
 
Mike Simmons
Ranch Hand
Posts: 3041
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Greenhorn
Posts: 20
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic