Adam Heath wrote:
public synchronized void fooMethod(Map map) {
    // do something
    boolean result = map.containsKey("foo");
    // do something else
}


public class MyMap extends Map {
    public synchronized Object get(Object key) {
        // do something
        fooMethod(this);
        // do something else
        return keyValue;
    }
}


The above seemingly simple code is dead-lock prone.  There is no way
to know what map.get() is actually doing.  It could post the update to
another thread, waiting for processing to occur(like some kind of
database transaction threadpool worker).

Basically, if you use synchronized, you have to be *very* careful
about the methods you call while you have a lock held.  There is no
guarantee about what locks the called code may be taking.  It might
even work now, but the library could change in the future to do
different locking.

This is good information, but... what is the correct way to do it? Can you give us a couple of refactoring examples?


Reply via email to