Is there a Java Stack replacement that doesn't sync?

I have a large code base (written by me) that uses a Stack data structure. This was used for convenience, and I use it as a Stack sometimes or Vector / List at another time.

After a performance review, it was decided that we did not want to pay extra for synchronization security. I now need to replace this structure with unsynchronized (and it is mentioned many times in the code).

I was glad to know that the Apache collections include the ArrayStack that I definitely want (just like the Java stack, but not in sync). However, this does not have generics, like modern Java 5 code (which I use). And I'm not going to convert my code to look like Java 1.4

So, is there any other replacement for Java 5 to replace Java Stack or do I need to write my own?

Update:

I used LinkedList with the configured pop / push methods.

+8
java stack data-structures
source share
2 answers

When you say "compatible with Java 5" - ArrayDeque<T> did not get to Java 6, but it sounds like you did after (using the Deque<T> interface, where necessary, of course). You can use it as a stack whenever you want, or a queue where it is more suitable ... just call the appropriate methods basically.

+8
source share

In your special case (and in fact only in that case), I simply copy and paste the Stack class from the open source Java SE implementation into my own package and delete all synchronized keywords. You can add extends java.util.Stack . Now you only need to change the import declarations in your code.

I understand that it is usually not recommended to copy the code, but this is why this does not apply to this case:

  • If the semantics of the pop() and push() stack are well suited to the current code, this does not change for performance reasons only. The semantics of the detex or linked list are different (they allow you to add / remove from both sides).
  • The synchronization overhead of java.util.Stack cannot be removed using another method, such as subclassing (calling super methods) or delegation.
  • Better to copy well-tested code (as far as the license permits) than to rewrite from scratch.

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

+1
source share

All Articles