“Stack”和”同步装饰器”(Synchronization Decorator)在ArrayDeque中的区别。

huangapple go评论79阅读模式
英文:

Difference between Stack and synchronization decorator for ArrayDeque

问题

我想要实现后进先出的效果,并且希望它是同步的。有人知道我应该使用这两种实现中的哪一种吗?我已经搜索了一段时间,但仍然没有得到很好的答案。

底线:它们之间有什么区别,为什么选择一种而不是另一种,为什么说

英文:

I want to have LIFO effect and I want it to be synchronized. Does anyone know which one of these two implementations I should use? Been googling for a while, still no good answer.

Bottom line: what are differences, why use one over another, why is it said to favor arrayDequeue?

答案1

得分: 2

从问题中:

> 为什么说要偏爱 ArrayDeque?

并不是说要偏爱 ArrayDeque(一个类)。

人们说你应该偏爱 Deque(一个接口),而不是 Stack(一个类),因为你应该按接口编程,允许你在不更改代码的情况下替换实现

人们说……”就在 Stack 的 Java 文档中:

> Deque 接口及其实现提供了一组更完整一致的后进先出堆栈操作,应优先使用它们,而不是此类。

Java 运行库提供了以下几种 Deque 的实现选择:

LinkedBlockingDeque 使用锁,类似于使用 synchronized,但其他几种都不使用 synchronizedConcurrentLinkedDeque 的线程安全实现方式已被证明比使用 synchronized 的实现性能更好。ArrayDequeStack 更快,因为它不使用 synchronized,所以对于非线程安全的代码更好。


另请参阅:为什么应该使用 Deque 而不是 Stack?
另请参阅:为什么 Java 的 Vector(和 Stack)类被视为过时或不推荐使用?

英文:

From question:

> why is it said to favor arrayDequeue?

It is not said to favor ArrayDeque (a class).

It is said that you should favor Deque (an interface) over Stack (a class), because you should program to an interface, allowing you to substitute the implementation without otherwise changing your code.

The "it is said ..." is right there in the javadoc of Stack:

> A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

The Java Runtime Library comes with the following choices of implementation for a Deque:

LinkedBlockingDeque uses locks, which is similar to using synthronized, but none of the others use synchronized. The way ConcurrentLinkedDeque is implemented to be thread-safe has proven to perform better than an implementation using synchronized. ArrayDeque is faster than Stack because it is not using synchronized, so is better for non-thread-safe code.


See also: Why should I use Deque over Stack?
See also: Why is Java Vector (and Stack) class considered obsolete or deprecated?

huangapple
  • 本文由 发表于 2020年8月21日 08:22:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63514869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定