• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Unit testing synchronized code

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 20
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic