为什么 Java Vector(和 Stack)类被认为已过时或已弃用? [英] Why is Java Vector (and Stack) class considered obsolete or deprecated?
问题描述
为什么 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
?
Stack
怎么样,它是Vector
的子类,应该用什么代替?
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
,您仍然需要取出一个锁以避免其他人同时更改集合,这会导致 Vector
code>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.
基本上,在大多数情况下,这是一种非常有缺陷的同步方法.正如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)类被认为已过时或已弃用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!