vector在Java中是什么结构,在Java中可以使用什么代替Vector?

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 v = new Vector();

解决方案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:

The list is thread-confined; i.e. only one thread ever can access it.

The list requires coarse-grained synchronization; i.e. exclusive access while performing a sequence of operations. In this case, you would typically create a custom class with an embedded (say) 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值