Example usage for java.util ArrayDeque ArrayDeque

List of usage examples for java.util ArrayDeque ArrayDeque

Introduction

In this page you can find the example usage for java.util ArrayDeque ArrayDeque.

Prototype

public ArrayDeque(Collection<? extends E> c) 

Source Link

Document

Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Usage

From source file:org.tango.server.attribute.log.AttributeAppender.java

public AttributeAppender(final int depth) {
    this.depth = depth;
    log = new ArrayDeque<Triple<String, String, String>>(depth);
}

From source file:RandomChooser.java

private RandomChooser(List<Double> weights, List<T> events, Random random) {
    double sum = 0.0;
    for (double prob : weights)
        sum += prob;/*w w  w  . ja  v  a 2 s.  c  o m*/

    this.probs = new double[weights.size()];
    for (int i = 0; i < weights.size(); i++) {
        probs[i] = weights.get(i) * weights.size() / sum; //average = 1.0
    }

    Deque<Integer> smaller = new ArrayDeque<Integer>(weights.size() / 2 + 2);
    Deque<Integer> greater = new ArrayDeque<Integer>(weights.size() / 2 + 2);
    for (int i = 0; i < probs.length; i++) {
        if (probs[i] < 1.0) {
            smaller.push(i);
        } else {
            greater.push(i);
        }
    }
    indexes = new int[weights.size()];
    while (!smaller.isEmpty()) {
        Integer i = smaller.pop();
        Integer k = greater.peek();
        indexes[i] = k;
        probs[k] -= (1 - probs[i]);
        if (probs[k] < 1.0) {
            greater.pop();
            if (greater.isEmpty())
                break;
            smaller.push(k);
        }
    }
    this.events = events;
    this.random = random;
}

From source file:actor4j.core.DefaultActorThread.java

public DefaultActorThread(ActorSystemImpl system) {
    super(system);

    directiveQueue = new MpscArrayQueue<>(system.getQueueSize());
    priorityQueue = new PriorityBlockingQueue<>(system.getQueueSize());
    serverQueueL2 = new MpscArrayQueue<>(system.getQueueSize());
    serverQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    outerQueueL2 = new MpscArrayQueue<>(system.getQueueSize());
    outerQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    innerQueue = new CircularFifoQueue<>(system.getQueueSize());

    newMessage = new AtomicBoolean(true);
}

From source file:uniol.apt.util.DifferentPairsIterable.java

@Override
public Iterator<Pair<E, E>> iterator() {
    return new Iterator<Pair<E, E>>() {
        private Deque<E> remainingElements = new ArrayDeque<>(collection);
        private Iterator<E> iter = emptyIterator();
        private E currentElement = null;

        @Override//  w ww. j a v  a 2s . c om
        public boolean hasNext() {
            while (!iter.hasNext()) {
                if (remainingElements.isEmpty())
                    return false;

                currentElement = remainingElements.remove();

                iter = remainingElements.iterator();
            }

            return true;
        }

        @Override
        public Pair<E, E> next() {
            if (!hasNext())
                throw new NoSuchElementException();
            return new Pair<>(currentElement, iter.next());
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.apache.tajo.engine.planner.global.ParallelExecutionQueue.java

private void toStacks(ExecutionBlock current, List<Deque<ExecutionBlock>> queues, List<ExecutionBlock> stack) {
    stack.add(current);/*from   w  w  w.j a  va  2s  .  co  m*/
    if (masterPlan.isLeaf(current.getId())) {
        queues.add(new ArrayDeque<>(stack));
    } else {
        List<ExecutionBlock> children = masterPlan.getChilds(current);
        for (int i = 0; i < children.size(); i++) {
            toStacks(children.get(i), queues, i == 0 ? stack : new Stack<>());
        }
    }
}

From source file:actor4j.core.XActorThread.java

public XActorThread(ActorSystemImpl system) {
    super(system);

    directiveQueue = new MpscArrayQueue<>(system.getQueueSize());
    priorityQueue = new PriorityBlockingQueue<>(system.getQueueSize());
    serverQueueL2 = new MpscArrayQueue<>(system.getQueueSize());
    serverQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    outerQueueL2B = new MpscLinkedQueue8<>();
    outerQueueL2A = new MpscArrayQueue<>(system.getQueueSize());
    outerQueueL1 = new ArrayDeque<>(system.getBufferQueueSize());
    innerQueueL2 = new LinkedList<>();
    innerQueueL1 = new CircularFifoQueue<>(system.getQueueSize());

    antiFloodingEnabled = new AtomicBoolean(false);

    newMessage = new AtomicBoolean(true);
}

From source file:org.polymap.core.runtime.event.AnnotatedEventListener.java

/**
 * //from  w w w.  j av  a2  s .  c om
 */
public AnnotatedEventListener(Object handler, Integer mapKey, EventFilter... filters) {
    assert handler != null;
    assert filters != null;
    this.handlerRef = new WeakReference(handler);
    this.handlerClass = handler.getClass();
    this.mapKey = mapKey;

    // find annotated methods
    Queue<Class> types = new ArrayDeque(16);
    types.add(handler.getClass());
    while (!types.isEmpty()) {
        Class type = types.remove();
        if (type.getSuperclass() != null) {
            types.add(type.getSuperclass());
        }
        types.addAll(Arrays.asList(type.getInterfaces()));

        for (Method m : type.getDeclaredMethods()) {
            EventHandler annotation = m.getAnnotation(EventHandler.class);
            if (annotation != null) {
                m.setAccessible(true);

                // annotated method
                AnnotatedMethod am = annotation.delay() > 0 ? new DeferredAnnotatedMethod(m, annotation)
                        : new AnnotatedMethod(m, annotation);

                EventListener listener = am;

                // display thread;
                if (annotation.display()) {
                    // if this is NOT the delegate of the DeferringListener then
                    // check DeferringListener#SessionUICallbackCounter
                    listener = new DisplayingListener(listener);
                }

                // deferred
                // XXX There is a race cond. between the UIThread and the event thread; if the UIThread
                // completes the current request before all display events are handled then the UI
                // is not updated until next user request; DeferringListener handles this by activating
                // UICallBack, improving behaviour - but not really solving in all cases; after 500ms we
                // are quite sure that no more events are pending and UI callback can turned off

                // currenty COMMENTED OUT! see EventManger#SessionEventDispatcher
                if (annotation.delay() > 0 /*|| annotation.display()*/) {
                    int delay = annotation.delay() > 0 ? annotation.delay() : 500;
                    listener = new TimerDeferringListener(listener, delay, 10000);
                }
                // filters
                listener = new FilteringListener(listener,
                        ObjectArrays.concat(am.filters, filters, EventFilter.class));

                // session context; first in chain so that all listener/filters
                // get the proper context
                SessionContext session = SessionContext.current();
                if (session != null) {
                    listener = new SessioningListener(listener, mapKey, session, handlerClass);
                }
                methods.add(listener);
            }
        }
    }
    if (methods.isEmpty()) {
        throw new IllegalArgumentException("No EventHandler annotation found in: " + handler.getClass());
    }
}

From source file:com.offbynull.peernetic.playground.chorddht.model.SuccessorTable.java

/**
 * Constructs a {@link SuccessorTable} object.
 * @param basePtr base pointer/*from  ww w .  jav a  2  s.  co  m*/
 * @throws NullPointerException if any arguments are {@code null}
 */
public SuccessorTable(InternalPointer basePtr) {
    Validate.notNull(basePtr);
    Id baseId = basePtr.getId();
    Validate.isTrue(IdUtils.isUseableId(baseId)); // make sure satisfies 2^n-1

    this.basePtr = basePtr;
    limit = IdUtils.getBitLength(baseId);

    table = new ArrayDeque<>(limit);
    table.add(basePtr);
}

From source file:au.org.ala.delta.intkey.directives.StandardIntkeyDirective.java

@Override
public IntkeyDirectiveInvocation doProcess(IntkeyContext context, String data) throws Exception {
    StringBuilder stringRepresentationBuilder = new StringBuilder();
    stringRepresentationBuilder.append(StringUtils.join(getControlWords(), " ").toUpperCase());

    List<String> tokens = ParsingUtils.tokenizeDirectiveCall(data);
    Queue<String> tokenQueue = new ArrayDeque<String>(tokens);

    IntkeyDirectiveInvocation invoc = buildCommandObject();

    if (_intkeyFlagsList != null && tokenQueue.size() > 0) {
        boolean matchingFlags = true;
        while (matchingFlags) {
            boolean tokenMatched = false;
            String token = tokenQueue.peek();

            if (token != null) {
                for (IntkeyDirectiveFlag flag : _intkeyFlagsList) {
                    if (flag.takesStringValue()) {
                        // Flag can have a string value supplied with it in
                        // format "/X=string", where X is the character
                        // symbol. Note that
                        // it is acceptable to supply such a flag without a
                        // following equals sign and string value.
                        if (token.matches("^/[" + Character.toLowerCase(flag.getSymbol())
                                + Character.toUpperCase(flag.getSymbol()) + "](=.+)?")) {

                            // If string value is not supplied, it defaults
                            // to empty string
                            String flagStringValue = "";

                            String[] tokenPieces = token.split("=");

                            // There should only be 0 or 1 equals sign. If
                            // more than none is supplied, no match.
                            if (tokenPieces.length < 3) {
                                if (tokenPieces.length == 2) {
                                    flagStringValue = tokenPieces[1];
                                }/*  ww  w  .j av a2 s.  c om*/

                                BeanUtils.setProperty(invoc, flag.getName(), flagStringValue);
                                tokenQueue.remove();
                                tokenMatched = true;
                                stringRepresentationBuilder.append(" ");
                                stringRepresentationBuilder.append(token);
                                break;
                            }
                        }
                    } else {
                        if (token.equalsIgnoreCase("/" + flag.getSymbol())) {

                            BeanUtils.setProperty(invoc, flag.getName(), true);
                            tokenQueue.remove();
                            tokenMatched = true;
                            stringRepresentationBuilder.append(" ");
                            stringRepresentationBuilder.append(token);
                            break;
                        }
                    }
                }

                matchingFlags = tokenMatched;
            } else {
                matchingFlags = false;
            }
        }
    }

    // The arguments list needs to be generated each time a call to the
    // directive is processed. This is
    // because most arguments need to have provided with an initial value
    // which is used when prompting the user.
    // This initial value needs to be read out of the IntkeyContext at the
    // time of parsing.
    // E.g. the integer argument for the SET TOLERANCE directive will have
    // an initial value equal to the
    // the value of the tolerance setting before the call to the directive.
    List<IntkeyDirectiveArgument<?>> intkeyArgsList = generateArgumentsList(context);

    if (intkeyArgsList != null) {
        for (IntkeyDirectiveArgument<?> arg : intkeyArgsList) {
            Object parsedArgumentValue = arg.parseInput(tokenQueue, context,
                    StringUtils.join(_controlWords, " "), stringRepresentationBuilder);
            if (parsedArgumentValue != null) {
                BeanUtils.setProperty(invoc, arg.getName(), parsedArgumentValue);
            } else {
                // No argument value supplied, user cancelled out of the
                // prompt dialog.
                return null;
            }
        }
    }

    invoc.setStringRepresentation(stringRepresentationBuilder.toString());

    return invoc;
}

From source file:eu.openanalytics.rsb.rservi.CircularRServiUriSelector.java

@PostConstruct
public void initialize() {
    final Map<String, Deque<URI>> newCircularApplicationUris = new HashMap<String, Deque<URI>>();

    final Map<String, Set<URI>> applicationSpecificRserviPoolUris = configuration
            .getApplicationSpecificRserviPoolUris();
    if ((applicationSpecificRserviPoolUris != null) && (!applicationSpecificRserviPoolUris.isEmpty())) {
        for (final Entry<String, Set<URI>> applicationSpecificRserviPoolUri : applicationSpecificRserviPoolUris
                .entrySet()) {//from  ww w  .  j a  va2s.  c  om
            newCircularApplicationUris.put(applicationSpecificRserviPoolUri.getKey(),
                    new ArrayDeque<URI>(applicationSpecificRserviPoolUri.getValue()));
        }
    }

    circularApplicationUris = Collections.unmodifiableMap(newCircularApplicationUris);
}