Hashmap concurrency issue

I have a Hashmap that, for speed reasons, I would like to not require locking on. Will updating it and accessing it at the same time cause any issues, assuming I don't mind stale data?

My accesses are gets, not iterating through it, and deletes are part of the updates.


Yes, it will cause major problems. One example is what could happen when adding a value to the hash map: this can cause a rehash of the table, and if that occurs while another thread is iterating over a collision list (a hash table "bucket"), that thread could erroneously fail to find a key that exists in the map. HashMap is explicitly unsafe for concurrent use.

Use ConcurrentHashMap instead.


The importance of synchronising or using ConcurrentHashMap can not be understated.

I was under the misguided impression up until a couple of years ago that I could get away with only synchronising the put and remove operations on a HashMap. This is of course very dangerous and actually results in an infinite loop in HashMap.get() on some (early 1.5 I think) jdk's.

What I did a couple of years ago (and really shouldn't be done):

public MyCache {
    private Map<String,Object> map = new HashMap<String,Object>();

    public synchronzied put(String key, Object value){
        map.put(key,value);
    }

    public Object get(String key){
        // can cause in an infinite loop in some JDKs!!
        return map.get(key);
    }
}

EDIT : thought I'd add an example of what not to do (see above)


When in doubt, check the class's Javadocs:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

(emphasis not mine)

So based on the fact that you said that your threads will be deleting mappings from the Map, the answer is that yes it will definitely cause issue and yes it is definitely unsafe .

链接地址: http://www.djcxy.com/p/91974.html

上一篇: <?之间的区别 超级T>和<? 在Java中扩展T>

下一篇: 散列图并发问题