In C ++, std :: vector
is used for variable length arrays, but in Java, java.util.ArrayList
is usually used, and java.util.Vector
, which seems to have similar functions, is used. not.
--It seems to be slow because it synchronizes
--If you want a synchronized list, you should use java.util.Collections.synchronizedList ()
I didn't care about it until now because I thought it might be the case when I heard a story like this, but I suddenly became interested, so I took a look at the OpenJDK source.
Certainly each method has a synchronized clause. You should definitely use ʻArrayList` when you don't need synchronization.
Vector.java
...
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
...
public synchronized boolean add(E e) {
modCount++;
add(e, elementData, elementCount);
return true;
}
...
So what is the difference between Vector and Collections.SynchronizedList (new ArrayList <> ())
wrapped with ʻArrayList? What is different at first glance is the behavior of Iterator. In
Vector`, the Iterator method also acquires the lock like other methods.
Vector.java
private class Itr implements Iterator<E> {
...
public E next() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor;
if (i >= elementCount)
throw new NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}
...
For SynchronizedCollections inherited by SyncronizedList, Iterator () returns the wrapped type as is.
Collections.java
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 3053995032091335093L;
final Collection<E> c; // Backing Collection
final Object mutex; // Object on which to synchronize
...
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
When iterating over a list, it's not enough to get the lock only within a single method, and after all you have to lock the entire iterative process, do it yourself ("Must be manually synched"). by user! ") Maybe that means.
--Vector
has synchronized for each method
--The behavior of iterator is different from SynchronizedList
Recommended Posts