This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
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.
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.