Is there a drop-in replacement for Java Stack that is not synchronized?
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 co开发者_开发技巧de 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.
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.
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()
andpush()
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 (callingsuper
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.
精彩评论