It took me a long time to believe this one was possible. You probably know that the Java collections aren't synchronised at the method level. Therefore, synchronised methods on collections give a false sense of security with respect to concurrent modification of the data contained therein. You may also know that if you are going to have two threads modifying the same object, you need to make sure they're not doing so at the same time. However, for some collections you must take care to make sure that even a read and a write don't happen at the same time. It's possible that the modifications made to the internal data storage in the collection are not atomic in nature, and while the writing thread modifies the collection, the reading thread can peek in and get undefined results. For instance, examine the code in Listing E. Since only one of the two threads is writing to the HashMap, it would seem at first glance that no synchronisation is necessary. However, it is possible that during the put action on the HashMap, a get will find the HashMap in an inconsistent state. Listing F shows the same code with a synchronised block added. Notice that the put and get can no longer happen at the same time. Synchronisation deadlock
When the data in two data sources must be kept cohesive in a multithreaded application, it's necessary to obtain the synchronisation lock for both data store objects before making any changes. Care must be taken to ensure that all code seeking to hold both monitors simultaneously obtains them in the same order. If, as shown in Listing G, one thread nests its synchronisation blocks in an order contrary to that of another thread vying for the same monitors, a deadlock can result. Each thread is stuck at the point indicated by the deadlock comment and is waiting for the release of the monitor that the other one already has. A subtler version of this problem appears in Listing H. Remember that synchronised methods are just standard synchronised blocks around the whole method using the object locally referenced by the reserved word this for locking. Fortunately, once found, the repair of these deadlocks is as simple as reordering the synchronisation for one of threads. Double-checked locking
I would be remiss if I didn't mention the class threading problem found in what's been dubbed "the Double-Check Idiom." Bill Pugh has written an excellent article explaining this most common and counterintuitive threading problem. Winding down
Threading can be a tricky affair. But once you've made every mistake once, you can put aside any dread associated with multithreaded code and start using it more and more. Sufficiently threaded code can, under the right conditions, leave program execution time completely I/O bound, which is a great way to answer any charges about Java's slowness.
Enterpise newsletter. Find out what's where in the new Tech Update with our
Guided Tour. Tell us what you think in the
Enterprise Mailroom.






