Why is Java Vector (and Stack) class considered obsolete or deprecated?(为什么 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.
基本上,在大多数情况下,这是一种非常有缺陷的同步方法.正如 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)类被认为已过时或不推荐使用?
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
