为什么Java Vector(和Stack)类被认为已过时或已弃用? [英] Why is Java Vector (and Stack) class considered obsolete or deprecated?

查看:657
本文介绍了为什么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?

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 ,您仍需要取出锁定以避免其他人同时更改集合,这会在迭代线程中导致 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 - 的事实向量将调整大小的数组集合实现与同步每个操作位相结合是另一个糟糕设计的例子;装饰方法可以更清晰地分离顾虑。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆