Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to test that a Java method is synchronized?

I have several classes that implement some interface. The interface has a contract, that some methods should be synchronized, and some should not, and I want to verify that contract through unit tests for all the implementations. The methods should use the synchronized keyword or be locked on this - very similar to the synchronizedCollection() wrapper. That means I should be able to observe it externally.

To continue the example of Collections.synchronizedCollection() if I have one thread calling iterator(), I should still be able to get into methods like add() with another thread because iterator() should not do any locking. On the other hand, I should be able to synchronize on the collection externally and see that another thread blocks on add().

Is there a good way to test that a method is synchronized in a JUnit test? I want to avoid long sleep statements.

like image 333
Craig P. Motlin Avatar asked Mar 05 '10 00:03

Craig P. Motlin


People also ask

How methods are synchronized in Java?

Java Synchronized MethodIf we use the Synchronized keywords in any method then that method is Synchronized Method. It is used to lock an object for any shared resources. The object gets the lock when the synchronized method is called. The lock won't be released until the thread completes its function.

How do we synchronize the test method in JUnit?

Instructions: #1 - RunSynchronize JUnit Tests once to create the @Testable annotation. #2 - Annotate desired source methods with @Testable annotation. #3 - Run Synchronize JUnit Tests to create test methods.

What does it mean if a method is synchronized?

Synchronized blocks or methods prevents thread interference and make sure that data is consistent. At any point of time, only one thread can access a synchronized block or method (critical section) by acquiring a lock. Other thread(s) will wait for release of lock to access critical section.

Which of these is synchronized in Java?

Synchronised in the sense of collection framework is thread-safety. Here Vector will providing thread-safety.


1 Answers

If you just want to check if a method has the synchronized modifier, aside from the obvious (looking at the source code/Javadoc), you can also use reflection.

Modifier.isSynchronized(method.getModifiers())

The more general question of testing if a method guarantees proper synchronization in all concurrency scenarios is likely to be an undecidable problem.

like image 81
polygenelubricants Avatar answered Oct 12 '22 23:10

polygenelubricants