How are Vector and Hashtable thread safe on a collection?

I know they both have thread safe methods. I want to know how they are thread safe? What is the implementation? This is a common question in all interviews.

+3


source to share


6 answers


Take a look inside the Vector and Hashtable code in OpenJDK , you will notice that most of the public methods are synchronized

, which is an implementation detail that makes the methods of both collections thread safe. Also note that other operations on these collections (such as iteration) require external synchronization for thread safety.



+1


source


This is not true. All of their methods are synchronized. They are not the same thing. Iterating over them is not and cannot be thread safe, unless the block containing the iteration is thread safe, for example. synchronized. Thus, the caller is still responsible for thread safety. For this reason, the new classes in Framework Collections did not have synchronized methods by default.



+1


source


The Vector class that comes with my Sun / Oracle JDK version, which is the 6th, uses synchronized methods like

public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
    throw new ArrayIndexOutOfBoundsException(index
                         + " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
}

      

All important methods are synchronized this way, right in the method signature.

Note, however, that this is not a mandala. The contract says you have to make it thread safe, it won't tell you how.

0


source


These classes are conditionally thread safe and it is not good style to use them. The best option is to use the java.util.concurrent classes. * (Like ConcurrentHashMap, CopyOnWriteArrayList, etc.) which are really thread safe and provide good performance.

eg. ConcurrentHashMap scales much better than synchronized HashMap: http://www.javamex.com/tutorials/concurrenthashmap_scalability.shtml

0


source


The problem with these two classes is that they give the impression of thread safety by providing synchronized methods, but their internal state can be changed using the iterators they give you access to.

Synchronization in this case buys the exclusivity of your threads in all synchronized methods, since they use the same synchronization lock.

0


source


This is terminology that indicates that methods in a class are thread safe, that is, synchronized! (A class itself cannot be a Threadsafe. Its just a way of saying it.)

0


source







All Articles