Java Code Examples for java.util.ArrayDeque#peek()

The following examples show how to use java.util.ArrayDeque#peek() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemplatableType.java    From zserio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Instantiates the referenced template using the given instantiation reference.
 *
 * @param instantiationReferenceStack Stack of instantiations leading to this instantiation.
 * @param instantiationPackage        Package where the template should be instantiated.
 *
 * @return Instantiated template.
 */
TemplatableType instantiate(ArrayDeque<TypeReference> instantiationReferenceStack,
        Package instantiationPackage)
{
    final TypeReference instantiationReference = instantiationReferenceStack.peek();
    final List<TemplateArgument> templateArguments = instantiationReference.getTemplateArguments();
    if (templateParameters.size() != templateArguments.size())
    {
        throw new ParserException(instantiationReference,
                "Wrong number of template arguments for template '" + getName() + "'! Expecting " +
                templateParameters.size() + ", got " + templateArguments.size() + "!");
    }

    TemplatableType instantiation = instantiateImpl(templateArguments, instantiationPackage);
    instantiation.instantiationReferenceStack = instantiationReferenceStack.clone();
    instantiation.template = this;
    instantiations.add(instantiation);
    return instantiation;
}
 
Example 2
Source File: VariousUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static String extractTypeFroVariableBase(VariableBase varBase, Map<String, AssignmentImpl> allAssignments) {
    ArrayDeque<VariableBase> stack = new ArrayDeque<>();
    String typeName = null;
    createVariableBaseChain(varBase, stack);
    while (!stack.isEmpty() && stack.peek() != null) {
        varBase = stack.pop();
        String tmpType = extractVariableTypeFromVariableBase(varBase, allAssignments);
        if (tmpType == null) {
            typeName = null;
            break;
        }
        if (typeName == null) {
            typeName = tmpType;
        } else {
            typeName += tmpType;
        }
    }
    return typeName; //extractVariableTypeFromVariableBase(varBase);
}
 
Example 3
Source File: ServiceAck.java    From aeron with Apache License 2.0 6 votes vote down vote up
static boolean hasReached(final long logPosition, final long ackId, final ArrayDeque<ServiceAck>[] queues)
{
    for (final ArrayDeque<ServiceAck> serviceAckQueue : queues)
    {
        final ServiceAck serviceAck = serviceAckQueue.peek();

        if (null == serviceAck)
        {
            return false;
        }

        if (serviceAck.ackId != ackId)
        {
            throw new ClusterException(ackId + " ack out of sequence " + serviceAck);
        }

        if (serviceAck.logPosition != logPosition)
        {
            throw new ClusterException(logPosition + " log position out of sequence " + serviceAck);
        }
    }

    return true;
}
 
Example 4
Source File: MultithreadingCorrectnessStackUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenArrayDeque_whenExecutedParallel_thenShouldFail() {

    ArrayDeque<Integer> deque = new ArrayDeque<>();

    // Serial execution of push on ArrayDeque will always result in correct execution.
    range(1, 10000).forEach(value -> deque.push(value));

    int sum = 0;
    while(deque.peek() != null) {
        sum += deque.pop();
    }

    Assert.assertEquals(49995000, sum);

    // Parallel execution of push on ArrayDeque will not result in correct execution.
    range(1, 10000).parallel().forEach(value -> deque.push(value));

    sum = 0;
    while(deque.peek() != null) {
        sum += deque.pop();
    }

    // This shouldn't happen.
    if(sum == 49995000) {
        System.out.println("Something wrong in the environment, Please try some big value and check");
        // To safe-guard build without test failures.
        return;
    }

    Assert.assertNotEquals(49995000, sum);
}
 
Example 5
Source File: AbstractSkylarkFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an extension from a {@code path}.
 *
 * @param loadImport an import label representing an extension to load.
 */
private ExtensionData loadExtension(LoadImport loadImport)
    throws IOException, BuildFileParseException, InterruptedException {
  ExtensionData extension = null;
  ArrayDeque<ExtensionLoadState> work = new ArrayDeque<>();
  work.push(
      new ExtensionLoadState(
          loadImport, getImportPath(loadImport.getLabel(), loadImport.getImport())));

  while (!work.isEmpty()) {
    ExtensionLoadState load = work.peek();
    extension =
        lookupExtensionForImport(load.getPath(), load.getSkylarkImport().getImportString());

    if (extension != null) {
      // It's possible that some lower level dependencies already loaded
      // this work item.  We're done with it, so pop the queue.
      work.pop();
      continue;
    }

    // Load BuildFileAST if needed.
    boolean astLoaded = maybeLoadAST(load);
    boolean haveUnsatisfiedDeps = astLoaded && processExtensionDependencies(load, work);

    // NB: If we have unsatisfied dependencies, we don't do anything;
    // more importantly we do not pop the work queue in this case.
    // This load is kept on the queue until all of its dependencies are satisfied.

    if (!haveUnsatisfiedDeps) {
      // We are done with this load; build it and cache it.
      work.removeFirst();
      extension = buildExtensionData(load);
      extensionDataCache.put(load.getPath(), extension);
    }
  }

  Preconditions.checkNotNull(extension);
  return extension;
}
 
Example 6
Source File: FtsTableInfo.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Parses FTS options from the create statement of an FTS table.
 *
 * This method assumes the given create statement is a valid well-formed SQLite statement as
 * defined in the <a href="https://www.sqlite.org/lang_createvtab.html">CREATE VIRTUAL TABLE
 * syntax diagram</a>.
 *
 * @param createStatement the "CREATE VIRTUAL TABLE" statement.
 * @return the set of FTS option key and values in the create statement.
 */
@VisibleForTesting
@SuppressWarnings("WeakerAccess") /* synthetic access */
static Set<String> parseOptions(String createStatement) {
    if (createStatement.isEmpty()) {
        return new HashSet<>();
    }

    // Module arguments are within the parenthesis followed by the module name.
    String argsString = createStatement.substring(
            createStatement.indexOf('(') + 1,
            createStatement.lastIndexOf(')'));

    // Split the module argument string by the comma delimiter, keeping track of quotation so
    // so that if the delimiter is found within a string literal we don't substring at the wrong
    // index. SQLite supports four ways of quoting keywords, see:
    // https://www.sqlite.org/lang_keywords.html
    List<String> args = new ArrayList<>();
    ArrayDeque<Character> quoteStack = new ArrayDeque<>();
    int lastDelimiterIndex = -1;
    for (int i = 0; i < argsString.length(); i++) {
        char c = argsString.charAt(i);
        switch (c) {
            case '\'':
            case '"':
            case '`':
                if (quoteStack.isEmpty()) {
                    quoteStack.push(c);
                } else if (quoteStack.peek() == c) {
                    quoteStack.pop();
                }
                break;
            case '[':
                if (quoteStack.isEmpty()) {
                    quoteStack.push(c);
                }
                break;
            case ']':
                if (!quoteStack.isEmpty() && quoteStack.peek() == '[') {
                    quoteStack.pop();
                }
                break;
            case ',':
                if (quoteStack.isEmpty()) {
                    args.add(argsString.substring(lastDelimiterIndex + 1, i).trim());
                    lastDelimiterIndex = i;
                }
                break;
        }
    }
    args.add(argsString.substring(lastDelimiterIndex + 1).trim()); // Add final argument.

    // Match args against valid options, otherwise they are column definitions.
    HashSet<String> options = new HashSet<>();
    for (String arg : args) {
        for (String validOption : FTS_OPTIONS) {
            if (arg.startsWith(validOption)) {
                options.add(arg);
            }
        }
    }

    return options;
}
 
Example 7
Source File: DfaAuxiliaryInformation.java    From dfalex with Apache License 2.0 4 votes vote down vote up
/**
 * Perform a depth first search of all states, starting at the start states
 * <P>
 * To avoid stack overflow errors on large DFAs, the implementation uses an auxiliary
 * stack on the heap instead of recursing
 * 
 * @param onEnter  called with (parent, child) when a child is entered.  parent == null for roots.
 * @param onSkip  called with (parent, child) when a child is skipped because it has been entered
 *                  previously.  parent == null for roots.
 * @param onLeave  called with (parent, child) when a child is exited.  parent == null for roots.
 */
public void depthFirstSearch(
        BiConsumer<DfaState<MATCHRESULT>, DfaState<MATCHRESULT>> onEnter,
        BiConsumer<DfaState<MATCHRESULT>, DfaState<MATCHRESULT>> onSkip,
        BiConsumer<DfaState<MATCHRESULT>, DfaState<MATCHRESULT>> onLeave)
{
    @SuppressWarnings("unchecked")
    final Iterator<DfaState<MATCHRESULT>>[] iterators = 
        (Iterator<DfaState<MATCHRESULT>>[]) new Iterator<?>[getStatesByNumber().size()];
    final ArrayDeque<DfaState<MATCHRESULT>> stack = new ArrayDeque<>();
    for (int rootIndex = 0; rootIndex < m_startStates.size(); ++rootIndex)
    {
        DfaState<MATCHRESULT> st = m_startStates.get(rootIndex);
        if (iterators[st.getStateNumber()] != null)
        {
            onSkip.accept(null, st);
            continue;
        }
        iterators[st.getStateNumber()] = st.getSuccessorStates().iterator();
        stack.push(st);
        onEnter.accept(null, st);
        for (;;)
        {
            //process the next child of the stack top
            st = stack.peek();
            final int sti = st.getStateNumber();
            final Iterator<DfaState<MATCHRESULT>> iter = iterators[sti];
            if (iter.hasNext())
            {
                final DfaState<MATCHRESULT> child = iter.next();
                if (child == null)
                {
                    //shouldn't happen, but if it does get the next child
                    continue;
                }
                final int childi = child.getStateNumber();
                if (iterators[childi] != null)
                {
                    onSkip.accept(st, child);
                }
                else
                {
                    iterators[childi] = child.getSuccessorStates().iterator();
                    stack.push(child);
                    onEnter.accept(st, child);
                }
            }
            else
            {
                //top element is done
                stack.pop();
                if (stack.isEmpty())
                {
                    onLeave.accept(null, st);
                    break;
                }
                onLeave.accept(stack.peek(), st);
            }
        }
    }
}
 
Example 8
Source File: TxDeadlockDetection.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param wfg Wait-for-graph.
 * @param txId Tx ID - start vertex for cycle search in graph.
 */
static List<GridCacheVersion> findCycle(Map<GridCacheVersion, Set<GridCacheVersion>> wfg, GridCacheVersion txId) {
    if (wfg == null || wfg.isEmpty())
        return null;

    ArrayDeque<GridCacheVersion> stack = new ArrayDeque<>();
    Set<GridCacheVersion> inPath = new HashSet<>();
    Set<GridCacheVersion> visited = new HashSet<>();
    Map<GridCacheVersion, GridCacheVersion> edgeTo = new HashMap<>();

    stack.push(txId);

    while (!stack.isEmpty()) {
        GridCacheVersion v = stack.peek();

        if (visited.contains(v)) {
            stack.pop();
            inPath.remove(v);

            continue;
        }

        visited.add(v);

        Set<GridCacheVersion> children = wfg.get(v);

        if (children == null || children.isEmpty()) {
            stack.pop();
            inPath.remove(v);

            continue;
        }

        inPath.add(v);

        for (GridCacheVersion w : children) {
            if (inPath.contains(w) && visited.contains(w)) {
                List<GridCacheVersion> cycle = new ArrayList<>();

                for (GridCacheVersion x = v; !x.equals(w); x = edgeTo.get(x))
                    cycle.add(x);

                cycle.add(w);
                cycle.add(v);

                return cycle;
            }

            edgeTo.put(w, v);
            stack.push(w);
        }
    }

    return null;
}