为什么 Java Vector(和 Stack)类被认为已过时或不推荐使用?

Why is Java Vector (and Stack) class considered obsolete or deprecated?(为什么 Java Vector(和 Stack)类被认为已过时或不推荐使用?)

本文介绍了为什么 Java Vector(和 Stack)类被认为已过时或不推荐使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Java Vector 被视为遗留类、已过时或已弃用?

Why is Java Vector considered a legacy class, obsolete or deprecated?

在处理并发时它的使用是否有效?

Isn't its use valid when working with concurrency?

如果我不想手动同步对象而只想使用线程安全的集合而不需要制作底层数组的新副本(如 CopyOnWriteArrayList 所做的那样),那么是可以使用Vector吗?

And if I don't want to manually synchronize objects and just want to use a thread-safe collection without needing to make fresh copies of the underlying array (as CopyOnWriteArrayList does), then is it fine to use Vector?

StackVector的子类,我应该用什么代替它?

What about Stack, which is a subclass of Vector, what should I use instead of it?

推荐答案

Vector 同步每个单独的操作.这几乎不是你想做的.

Vector synchronizes on each individual operation. That's almost never what you want to do.

通常您希望同步整个操作序列.同步单个操作都不太安全(例如,如果您遍历 Vector,您仍然需要取出锁以避免其他人同时更改集合,这会导致 ConcurrentModificationException 在迭代线程中)但也更慢(为什么一次就足够了,为什么要重复取出锁)?

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

当然,它也有锁定的开销,即使你不需要.

Of course, it also has the overhead of locking even when you don't need to.

基本上,在大多数情况下,这是一种非常有缺陷的同步方法.正如 Mr Brian Henk 指出的那样,您可以使用诸如 Collections.synchronizedList - Vector 结合了带有同步每个操作"位的调整大小数组"集合实现是糟糕设计的另一个例子;装饰方法可以更清晰地分离关注点.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

至于 Stack 等价物 - 我先看看 Deque/ArrayDeque.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

这篇关于为什么 Java Vector(和 Stack)类被认为已过时或不推荐使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 Java Vector(和 Stack)类被认为已过时或不推荐使用?

基础教程推荐