They’re always a question that comeback either in interview or when you are playing old code.
Why the hell are they using Vector over arrayList ?
Vector is a class that exists since the beginning of java (aka Java 1.0) it’s implement List. It seems to pollute old code and still use programmer that don’t know that there is better alternative.
Common knowledge and our teacher use to tell us that the difference between Vector and arrayList is that Vector is synchronized and ArrayList is not, which is true… But what it fails to explain is that you should not use Vector for synchronized operation either. Why ?
Because it’s synchronizes on each individual operation. That’s almost never what you want to do.
Normally if you really need synchronization you want to synchronize a whole sequence of operations, not just the individual operation.
Because even if the add, remove or get operation is synchronized you still need to have a lock to avoid anyone changing the collection at the same time (preventing those pesky ConcurrentModificationException) and it also slower because it lock on each access when once would be enough.
Instead use a ArrayList and use Collections.synchronizedList on your array list when you truly need synchronization.
If you want something more efficient that the Collections.synchronizedList and you are using JDK 1.5 and higher. There is a good concurrent collections that have been introduced in java 1.5. The name of that collection is CopyOnWriteArrayList, it’s highly efficient for high volume , low latency system.
While the Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List.
Several factors make them unsuitable for use in highly concurrent applications — their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationExceptions.
The CopyOnWriteArrayList implementation provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. CopyOnWriteArrayList are not necessarily useful everywhere you might use ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.
Recent Comments