Is there a drop-in replacement for Java Stack that

2020-07-08 07:21发布

I have a large codebase (written by me) that uses the Stack data structure. This was used for convenience and I am using it as Stack sometimes or Vector/List some other times.

After a performance review however it was decided that we do not want to pay extra for the synchronization safety. I need now to replace this structure with a non-synchronized one (and it is mentioned a lot of times in the code).

I was happy to discover that Apache collections includes an ArrayStack which is exactly what I want (same as Java stack but non-synchronized). However this does NOT have generics as modern Java 5 code (which is what I use). And I am not going to convert my code to look like Java 1.4

So is there any other Java 5 compliant drop-in replacement for Java Stack or do I need to write my own?

Update:

I used LinkedList with tuned "pop"/"push" methods.

2条回答
Anthone
2楼-- · 2020-07-08 07:40

When you say "Java 5 compliant" - ArrayDeque<T> didn't arrive until Java 6, but sounds like what you're after (using the Deque<T> interface where appropriate, of course). You can use it as a stack when you want to, or a queue where that's more appropriate... just call the appropriate methods, basically.

查看更多
迷人小祖宗
3楼-- · 2020-07-08 07:47

In your special case (and actually only in such a case), I'd simply copy and paste the Stack class from an open source Java SE implementation into your own package, and remove all synchronized keywords. You may want to add extends java.util.Stack. Now you'll only have to change the import declarations in your code.

I do realize, that typically it's not a good idea to copy code, but here's why this doesn't apply to this case:

  • If the the pop() and push() semantics of a Stack fit well for the current code, then this doesn't change just because of performance considerations. The semantics of a deque or linked list are different (they allow to add/remove from both sides).
  • The synchronization overhead of java.util.Stack cannot be removed by another technique like subclassing (calling super methods) or delegation.
  • It's better to copy well tested code (as far as the license allows it), than to rewrite from scratch.

In general, it would be a lot better to use java.util.Stack as if it were an interface, and not to use new Stack() in the code, but to instantiate it by using factories.

查看更多
登录 后发表回答