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)类被认为已过时或不推荐使用?
				
        
 
            
        - 转换 ldap 日期 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 
						
						
						
						
						
				
				
				
				