Re: How to extend the ConcurrentHashMap ?
Fab4J wrote:
I realize a multithreaded application in 5.0 EE environment. I need to
use the ConcurrentHashMap to ensure the multi thread access.
ConcurrentHashMap is good when a map is highly contended. If you just
want a map that is thread-safe, Collections.synchronizedMap or Hashtable
will do as well.
For the moment I add my own synchronized methods in a extensive class
like this :
public class MyMap<K, V> extends ConcurrentHashMap<K,V> {
public synchronized void removeAll(Filter filter) {
// no filter
if (filter == null) {
clear();
}
It would be better to just NPE rather than try to force some "clever"
interpretation on null.
//filtered
for (K key : keySet()) {
if (filter.accept(key)) {
remove(key);
}
}
}
}
However I have synchronized my method, I'm not sure that's so simple.
Especially, I'm not sure that the lock used during standard map access
is the same than the one used in my method (in fact, the
ConcurrentHashMap used an inner ReentrantLock)
In fact it uses a number of ReentrantLocks (the map is divided into
segments, only one of which (determined by key hashCode) needs to be
held for simple operations). Therefore, the synchronized will not help
you, but it doesn't really hurt either (other than being entirely
misleading).
The iterator of ConcurrentHashMap.keySet is sufficiently constrained to
be usable on a concurrently mutated map. So, you may try to remove a key
that has already been removed (not a problem). An entry may be added by
another thread with key k1, then after a with a key k2, but you may well
remove k2 but not k1.
If that sort of thing is not a problem for you, then all you need to do
is removed the synchronized. If it is a problem, then you need to use
some other map implementation. If you are writing code with a license
compatible with Commons Creative, then I guess you could download the
ConcurrentHashMap code from Doug Lea's site. If you don't need the high
contention performance, then I suggest Collections.synchronizedMap or
Hashtable.
Tom Hawtin
BTW: Why choose comp.lang.java.advocacy? I have set Followup-To and
cross posted to comp.lang.java.programmer.