Joshua Bloch's Effective Java, Second Edition, item 69 , states that
[...] To provide high concurrency, these implementations manage their own synchronization internally (Item 67). Therefore, it is impossible to exclude concurrent activity from a concurrent collection; locking it will have no effect but to slow the program.
Is this last statement correct? If two threads lock the collection and perform several operations within that lock, these operations might still be interleaved?
For the statement to be correct I would expect that either these collections run threads internally with which you cannot synchronize, or they somehow "override" the standard synchronization behavior such that a statement like synchronized(map){ ... }
behaves different than on a 'normal' object. From the answers/comments to related questions I think neither if these is true:
To avoid possible misinterpretation:
- I'm aware that concurrent collections are designed exactly to avoid this global locking, my question is whether it's possible in principle
- I find Effective Java an excellent book and I'm just seeking clarity on a particular item.
Sources suggest that
ConcurrentHashMap
uses an internal mechanism for locking (static final class [More ...] Segment<K,V> extends ReentrantLock
) and does not therefore use anysynchronized
methods for it's locking mechanism.It should therefore be simple to use the
Map
as a lock andsynchronize
on it - in the same way you could use anew Object()
or your ownReentrantLock
. However, it would not affect the inner workings of theMap
which is - I think - what he is trying to say.