views:

162

answers:

6

How to determine part of what Java code needs to be synchronized? Are there any unit testing technics?

Samples of code are welcome.

+8  A: 

Code needs to be synchronized when there might be multiple threads that work on the same data at the same time.

Whether code needs to be synchronized is not something that you can discover by unit testing. You must think and design your program carefully when your program is multi-threaded to avoid issues.

A good book on concurrent programming in Java is Java Concurrency in Practice.

Jesper
+1: the design should take account of concurrency. You probably won't discover all the places where you need to synchronize with testing. Instead you'll implement a system that tends to fall over under heavy load.
Stephen C
+1 for "not something that you can discover by unit testing", although you might be able to find a small proportion of flaws through processor-heavy testing.
Tom Hawtin - tackline
+3  A: 

This is a good source for some general information: http://weblogs.java.net/blog/caroljmcdonald/archive/2009/09/17/some-java-concurrency-tips

When you are in a multithreaded environment in Java and you want to do many things in parallel, I would suggest using an approach which uses the concurrent Queue (like BlockingQueue or ConcurrentLinkedQueue) implementations and a simple Runnable that has a reference to the queue and pulls 'messages' of the queue. Use an ExecutorService to manage the tasks. Sort of a (very simplified) Actor type of model.

So choose not to share state as much as possible, because if you do, you need to synchronize, or use a data structure that supports concurrent access like the ConcurrentHashMap.

Raymond Roestenburg
+3  A: 

If I understand your question correctly, you want to know what you have to synchronise. Unfortunately there isn't a boiler plate code to provide that shows you what to synchronise - you should take a look at methods and instance variables that can be accessed by multiple threads at the same time. If there aren't such, you usually don't need to worry about synchronisation too much.

msparer
+1  A: 

There's no substitute for thinking about the issues surrounding your code (as the other answers here illustrate). Once you've done that, though, it's worth running FindBugs over your code. It will identify where you've applied synchronisation inconsistently, and is a great help in tracking otherwise hard-to-find bugs.

Brian Agnew
A: 

Yes, all these folks are right - no alternative for thinking. But here is the thumb rule.. 1. If its a read - perhaps you do not need synchronization 2. If its a 'write' - you should consider it...

Ameya