commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Jack, Paul" <pj...@sfaf.org>
Subject FastArrayList, FastHashMap, FastTreeMap not thread safe
Date Tue, 09 Apr 2002 21:55:12 GMT
Hi,

I noticed that version 2.0 of the Commons Collections
has been released so I thought I'd browse through the
code.  While doing so I noticed something about 
FastArrayList, FastHashMap and FastTreeMap.

List and Map objects can return views on their contents
that can be modified.  For instance, elements can be 
removed from an ArrayList via its iterator().  Elements
can be removed from a map via its keySet() or its values()
collection.  A TreeMap can also return a submap that can
be modified.  Generally, changes on a view of a collection
are reflected in the original and vice-versa.

The problem is, with FastArrayList or FastHashMap, in "fast"
mode, if somebody tries to modify a collection view (say, a
keySet() of a FastHashMap) they will never enter the FastHashMap's
monitor.  The state of the FastHashMap can become corrupted if
more than one thread attempts to modify its keySet(); and threads
attempting a fast get(Object) on a FastHashMap while another
thread modifies its keySet() may get faulty data back.

I'd recommend using the "unmodifiable" methods of the 
java.util.Collections class to make the collection views immutable.
This would solve the problem, but technically violate the contract
of java.util.Map and java.util.List (which specify that views on
a map or list must support all operations the original map or list
supported).  

Here's the list of methods that worry me:

FastArrayList.iterator()
FastArrayList.subList(int, int)

FastHashMap.keySet()
FastHashMap.entrySet()
FastHashMap.values()

FastTreeMap.keySet()
FastTreeMap.entrySet()
FastTreeMap.values()
FastTreeMap.subMap(Object, Object)
FastTreeMap.headMap(Object)
FastTreeMap.tailMap(Object)

Here's a sample fixed implementation of FastHashMap.keySet():

public Set keySet() {
    if (fast) {
        return Collections.unmodifiableSet(map.keySet());
    } else {
        synchronized (map) {
            return map.keySet();
        }
    }
}

============================================
Paul Jack
Database Administrator
San Francisco AIDS Foundation
pjack@sfaf.org
(415)487-3075

"As far as we can discern, the sole purpose
of human existence is to kindle a light of
meaning in the darkness of mere being."
 --Carl Jung
============================================

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message