All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.conversantmedia.util.collection.FixedStack Maven / Gradle / Ivy

There is a newer version: 1.2.8-JDK7
Show newest version
package com.conversantmedia.util.collection;

/*
 * #%L
 * Conversant Disruptor
 * ~~
 * Conversantmedia.com © 2016, Conversant, Inc. Conversant® is a trademark of Conversant, Inc.
 * ~~
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/**
 * A very high performance stack to replace java.util.Stack.  This
 * stack wraps around rather than checking for bounds.
 *
 * The java version of Stack is based on Vector and completely outdated.
 * The performance of java.util.Stack is poor at best.
 *
 * This version is a small fast fixed size stack.   There
 * is no bounds checking so it should only be used when the stack size is known
 * in advance.
 *
 * This object is not thread safe.
 *
 * @author John Cairns  {@literal } Date: 7/9/12 Time: 8:53 AM
 */
public class FixedStack implements Stack {
    private final int size;
    private final int mask;
    private final N[] stack;
    private int   stackTop;

    /**
     *   construct a new stack of given capacity
     * 
     * @param size - the stack size 
     */
    public FixedStack(final int size) {
        int stackSize = 1;
        while(stackSize < size) stackSize <<=1;
        this.size = stackSize;
        this.mask = this.size-1;
        stack = (N[])new Object[stackSize];
        stackTop=0;
    }

    /**
     *  add an element to the stack
     *
     * @param n - the element to add
     * @return boolean - true if the operation succeeded
     */
    @Override
    public boolean push(final N n) {
        if(stackTop < size) {
            stack[(stackTop++) & mask] = n;
            return true;
        }
        return false;

    }

    @Override
    public boolean contains(final N n) {
        for(int i=0; i




© 2015 - 2025 Weber Informatics LLC | Privacy Policy