java.util.Vector
소개
대부분의 경우에 안 쓰는 것이 권장되는 Vector이긴 하지만 자꾸만 보여서 정리. 일단 Java Vector 문서에 따르면 첫 소개가 아래와 같음.
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
설명만 보면 ArrayList가 떠오름. 그래서 주로 ArrayList와 비교하여 정리함.
synchronized
ArrayList와 다르게 synchronized.- 그 만큼 오버헤드가 따름.
CopyOnWriteArrayList
- 그런데 동기화가 얼만큼 필요한지 생각해 볼 필요 있음.
- 많은 경우에 쓰기에 대해서만 동기화가 필요하고 읽기에는 필요 없음.
- 이 때
CopyOnWriteArrayList를 고려. - 읽기 시 성능에 유리.
- 하지만 주의할 점이 있음.
- iterator가 concurrent modification를 지원.
- 언뜻 보면 좋아보이나, 이를 위해 컬렉션 수정 시 매번 복제가 일어남.
- 잦은 수정에는 부담인 것.
Collections.synchronizedList
- 한편, 정말 모든 연산에 동기화가 필요할 수도.
- 하지만 이 때도
Collections.synchronizedList사용을 고려. - 이는
Vector에게 열려 있는elements(legacy) 사용을 피할 수 있게 도와줌. Enumeration을 반환하기에 fail-fast 하지 않음.- fail-fast에 대한 내용은 아래에 명시. 이 내용은 자바 컬렉션 클래스 문서마다 보이는 듯.
The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the vector is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
- 여기도 함께 참고.
growable array of objects
Vector또한ArrayList처럼 동적으로 크기를 늘림.- 하지만
ArrayList가 현재 크기의 50%만 늘어나는 반면에Vector는 100%. - 여기서 늘어난다는 것은 vector의 size가 아닌 capacity라는 점에 유의.
Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector’s storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
© 2020 codehumane ― Powered by Jekyll and Textlog theme