It looks like when programming in Java we are not suppose to use Vectors anymore when threads are involved.
What class should I use instead of a Vector when using threads?
import java.util.Vector;
Vector<String> v = new Vector<String>();
It looks like when programming in Java we are not suppose to use Vectors anymore when threads are involved.
You need to understand why using Vector
is considered to be a bad thing in most contexts. The reasons are:
Vector
synchronizes on every operation. Most contexts do not require fine-grained synchronization, and as such it is an unwanted performance overhead.
The Vector.elements()
method returns an Enumeration
which does not have fail-fast semantics.
Bringing this back to your question. The alternatives depend on what your threads are trying to do:
If the use-case does not require synchronization at all, use ArrayList
, or LinkedList
. You would typically use these if:
ArrayList
that is not exposed in the custom classes API.If the use-case requires fine-grained synchronization, Collections.synchronizedList
wrapper is equivalent to a Vector
. Alternatively, you could stick with Vector
and avoid using the elements()
operation.
A CopyOnWriteArrayList
list has the advantage that its iterator supports concurrent modification ... in a sense. It also scales better if your application mostly performs read the list. Read operations don't need to explicitly synchronize at all, and typically just need to read a single volatile
once. But the flip side is that write operations do synchronize, and are significantly more expensive than a "normal" ArrayList
.
The other problem with Vector
and the Collections.synchronizedList
wrapper is that some use-cases require coarser synchronization; e.g. testing a list's size and conditionally adding an element in a single synchronized operation. The Queue
and Deque
classes provide higher level abstractions that deal with this kind of thing ... for the use-cases involving passing work asynchronously from one thread to another.
The bottom line is that there is not one-size-fits-all solution. You need to understand the concurrency characteristics of your application design, and choose your data structures accordingly.
Finally, if you are programming for Java ME, you may be stuck with using Vector
, depending on what J2ME profile you are targeting.
List<String> list = Collections.synchronizedList(new ArrayList<String>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With