Synchronized collections
The synchronized collections are collections with the atomic operations. This means, only one thread can perform a collection operation at time.
You can make synchronized collection from any non-synchronized collection by Collections.synchronizedXXX() methods.
You must explicitly synchronize the collection when traversing it. Otherwise, you might get a ConcurrentModificationException if another thread modifies the collection.
List<String> lst = Collections.synchronizedList(new LinkedList<>());
synchronized(lst){
for(String el: lst){
// ...
}
}
Map<String, String> syncMap = Collections.
synchronizedMap(new HashMap<String, String>);
Set<String> keys = m.keySet(); // Needn't be in synchronized block
synchronized(syncMap) { // Synchronizing on syncMap, not keys!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Vector
Synchronized list based on array. version of ArrayList. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
Stack
Represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack.
method | description |
---|---|
empty() | Tests if this stack is empty. |
peek() | Looks at the object at the top of this stack without removing it from the stack. |
pop() | Removes the object at the top of this stack and returns that object. |
push(item) | Pushes an item onto the top of this stack. |
search(o) | Returns the 1-based position where an object is on this stack. Value -1 indicates that the object is not on the stack. |
Hashtable
Synchronized implementation of Map. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.