I need to synchronize the elements in the map depending on the key. If 2 threads calling getID(ID_0), and setID(ID_2, System.currentTimeMillis()), will the synchronized block not to block setID while getID is calling.

They won't block each other as long as the ID is different, but this code won't work. You must either synchronise on the HashMap, which destroys your objective, or else use a ConcurrentHashMap, which doesn't destroy it. However the operations you are protecting are so quick that I don't believe your original objective is necessary, and that synchronising on the HashMap is sufficient.

You mean even the id initialized as a final static String, and I mark it as final in the method param , it still will not doing the job? I just make a simple example. In fact, there are more code inside the synchronized block.

I just want to protect the Calendar object in the map, not the map. The map is only a container to me. If I synchronize the whole map every time update one of the entry in the map. Do you think it is efficient?

If you aren't changing the map, then it's a red herring for your question. If you want to prevent simultaneous modifications of a Calendar object, then the logical approach would be to synchronize on that Calendar object. The fact that you happen to have a map entry which contains a reference to the object shouldn't have anything to do with it.

Map is really very efficient, thus in this case a simple global lock is enough. But if you have similar case where read and write operations takes more time then it could be useful to take a look at ReadWriteLock or MultiLock.

zarr wrote:
Take a look at your example below rewritten with MultiLock:

A fine example indeed and a great way to shamelessly promote your library, but the OP had problems with the basics of concurrency and synchronization, something that can't be fixed by just throwing a library at them.

If you see any problems in MultiLock please tell me, I whould like to discuss them. I just want find out the method how to develop software without deadlocks. And such use cases in forums is a posibility find the truth :)