Java Code Examples for java.util.Queue

The following are top voted examples for showing how to use java.util.Queue. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JavaStudy   File: JDKQueue.java   Source Code and License 6 votes vote down vote up
public void jdkQueue() {
    Queue<Integer> queue = new LinkedList<Integer>();
    PrinterUtils.printELog("队列大小:" + queue.size());

    Integer arr[] = {1, 2, 3, 4, 5};
    //队列里放元素
    for (int i : arr) {
        queue.offer(i);
    }
    PrinterUtils.printELog("队列大小:" + queue.size());

    //移除
    while (!queue.isEmpty()) {
        PrinterUtils.printELog(
                "队列头部元素:" + queue.peek() +
                        ",出队:" + queue.poll());
    }


}
 
Example 2
Project: fresco_floodlight   File: DeviceManagerImpl.java   Source Code and License 6 votes vote down vote up
/**
* Send update notifications to listeners
* @param updates the updates to process.
*/
protected void processUpdates(Queue<DeviceUpdate> updates) {
if (updates == null) return;
DeviceUpdate update = null;
while (null != (update = updates.poll())) {
	if (logger.isTraceEnabled()) {
		logger.trace("Dispatching device update: {}", update);
	}
	if (update.change == DeviceUpdate.Change.DELETE) {
		deviceSyncManager.removeDevice(update.device);
	} else {
		deviceSyncManager.storeDevice(update.device);
	}
	List<IDeviceListener> listeners = deviceListeners.getOrderedListeners();
	notifyListeners(listeners, update);
}
}
 
Example 3
Project: openjdk-jdk10   File: ArrayDequeTest.java   Source Code and License 6 votes vote down vote up
/**
 * A deserialized/reserialized deque has same elements in same order
 */
public void testSerialization() throws Exception {
    Queue x = populatedDeque(SIZE);
    Queue y = serialClone(x);

    assertNotSame(y, x);
    assertEquals(x.size(), y.size());
    assertEquals(x.toString(), y.toString());
    assertEquals(Arrays.toString(x.toArray()), Arrays.toString(y.toArray()));
    assertTrue(Arrays.equals(x.toArray(), y.toArray()));
    while (!x.isEmpty()) {
        assertFalse(y.isEmpty());
        assertEquals(x.remove(), y.remove());
    }
    assertTrue(y.isEmpty());
}
 
Example 4
Project: vertx-ssdb   File: CompositeClient.java   Source Code and License 6 votes vote down vote up
void sendCommand(Handler<AsyncResult<Queue<byte[]>>> handler, String key, Object... params)
{
    if (batches != null) {
        batches.add(new BatchCommand(key, params, handler));
        return;
    }

    switch (status) {
        case Normal:
            connecter.tryGetConnection(F.ofSucceededVoid(handler, conn -> conn.execute(key, params, handler)));
            break;
        case Once:
            connecter.tryGetConnection(F.ofSucceededVoid(handler, conn -> conn.execute(key, params, F.ofSucceeded(handler, () -> {
                status = Status.Unusable;
                vertx.runOnContext(event -> close(F.noneHandle()));
            }, queue -> queue))));
            break;
        case Unusable:
            handler.handle(F.failedFuture(new SSDBClosedException()));
            break;
    }
}
 
Example 5
Project: JRediClients   File: PubSubConnectionEntry.java   Source Code and License 6 votes vote down vote up
public boolean removeListener(String channelName, EventListener msgListener) {
    Queue<RedisPubSubListener<?>> listeners = channelListeners.get(channelName);
    for (RedisPubSubListener<?> listener : listeners) {
        if (listener instanceof PubSubMessageListener) {
            if (((PubSubMessageListener)listener).getListener() == msgListener) {
                removeListener(channelName, listener);
                return true;
            }
        }
        if (listener instanceof PubSubPatternMessageListener) {
            if (((PubSubPatternMessageListener)listener).getListener() == msgListener) {
                removeListener(channelName, listener);
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Project: Nird2   File: ValidationManagerImpl.java   Source Code and License 6 votes vote down vote up
@ValidationExecutor
private void validateMessage(Message m, Group g) {
	MessageValidator v = validators.get(g.getClientId());
	if (v == null) {
		if (LOG.isLoggable(WARNING))
			LOG.warning("No validator for " + g.getClientId().getString());
	} else {
		try {
			MessageContext context = v.validateMessage(m, g);
			storeMessageContextAsync(m, g.getClientId(), context);
		} catch (InvalidMessageException e) {
			if (LOG.isLoggable(INFO))
				LOG.log(INFO, e.toString(), e);
			Queue<MessageId> invalidate = new LinkedList<MessageId>();
			invalidate.add(m.getId());
			invalidateNextMessageAsync(invalidate);
		}
	}
}
 
Example 7
Project: advent-of-code-2017   File: Day12.java   Source Code and License 6 votes vote down vote up
private static List<Integer> createConnectedComponent(HashMap<Integer, List<Integer>> graph, int root) {
	
	Queue<Integer> q = new ArrayDeque<>(); // next nodes to visit
	List<Integer> visited = new ArrayList<>(); // connected component so far
	q.add(root); // init queue

	while (!q.isEmpty()) {
		Integer poll = q.poll(); // get next node
		if (!visited.contains(poll)) { // if it's not already visited
			visited.add(poll); // visit it
			q.addAll(graph.get(poll)); // and put its neighbourhood in the queue
		}
	}
	visited.forEach(v -> graph.remove(v)); // removes the connected component from the graph
	return visited;
	
}
 
Example 8
Project: SimpleCalculator   File: ParseStrategyImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void parseTokensToValuesAndOperations(int j, String token, Queue<Float> values, Queue<String> operations) {
    switch (token) {
        case PLUS_CHAR:
        case MINUS_CHAR:
            // adding 0 as a first value when nothing before to start with a pair of values
            if (j == 0) {
                values.add(0f);
            }
            operations.add(token);
            break;
        default:
            values.add(Float.parseFloat(token));
            break;
    }
}
 
Example 9
Project: APCSAB   File: ZhuZhiyu_Period1_BinaryTreeLab.java   Source Code and License 6 votes vote down vote up
public static int width(TreeNode t) {
    int maxWdith = 0, levelWidth = 0;
    Queue<TreeNode> q = new LinkedList<>();
    q.add(t);
    q.add(null);
    while (!q.isEmpty()) {
        if (null == (t = q.poll())) {
            if (levelWidth > maxWdith)
                maxWdith = levelWidth;
            levelWidth = 0;
            if (null != q.peek()) q.add(null);
        } else {
            levelWidth++;
            if (null != t.getLeft()) q.add(t.getLeft());
            if (null != t.getRight()) q.add(t.getRight());
        }
    }
    return maxWdith;
}
 
Example 10
Project: UF-CPP   File: HV_CourseSchedule.java   Source Code and License 6 votes vote down vote up
public Set<Vertex> topologicalSort(Vertex startNode,Set<Vertex> set){
	Queue<Vertex> queue=new LinkedList<>();
	queue.add(startNode);
	
	while(!queue.isEmpty()){
		Vertex u=queue.poll();
		set.add(u);
		for(Vertex v : u.adjacents)
		{
			if(!set.contains(v)){
			v.inDegree--;
			if(v.inDegree==0)
				queue.add(v);
			}
			else
				return new HashSet<Vertex>();
		}
	}
	
	return set;
	
}
 
Example 11
Project: openjdk-jdk10   File: ConcurrentQueueLoops.java   Source Code and License 6 votes vote down vote up
void test(final Queue<Integer> q) throws Throwable {
     System.out.println(q.getClass().getSimpleName());
     pool = Executors.newCachedThreadPool();
     print = false;

     print = false;
     System.out.println("Warmup...");
     oneRun(1, items, q);
     oneRun(3, items, q);
     print = true;

     for (int i = 1; i <= maxStages; i += (i+1) >>> 1) {
         oneRun(i, items, q);
     }
     pool.shutdown();
     check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
 
Example 12
Project: jdk8u-jdk   File: RemovePollRace.java   Source Code and License 6 votes vote down vote up
Collection<Queue<Boolean>> concurrentQueues() {
    List<Queue<Boolean>> queues = new ArrayList<Queue<Boolean>>();
    queues.add(new ConcurrentLinkedDeque<Boolean>());
    queues.add(new ConcurrentLinkedQueue<Boolean>());
    queues.add(new ArrayBlockingQueue<Boolean>(count, false));
    queues.add(new ArrayBlockingQueue<Boolean>(count, true));
    queues.add(new LinkedBlockingQueue<Boolean>());
    queues.add(new LinkedBlockingDeque<Boolean>());
    queues.add(new LinkedTransferQueue<Boolean>());

    // Following additional implementations are available from:
    // http://gee.cs.oswego.edu/dl/concurrency-interest/index.html
    // queues.add(new SynchronizedLinkedListQueue<Boolean>());

    // Avoid "first fast, second slow" benchmark effect.
    Collections.shuffle(queues);
    return queues;
}
 
Example 13
Project: Jupiter   File: Level.java   Source Code and License 6 votes vote down vote up
private void computeSpreadBlockLight(int x, int y, int z, int currentLight, Queue<Vector3> queue,
                                     Map<BlockVector3, Boolean> visited) {
    int current = this.getBlockLightAt(x, y, z);
    BlockVector3 index = Level.blockHash(x, y, z);

    if (current < currentLight) {
        this.setBlockLightAt(x, y, z, currentLight);

        if (!visited.containsKey(index)) {
            visited.put(index, true);
            if (currentLight > 1) {
                queue.add(new Vector3(x, y, z));
            }
        }
    }
}
 
Example 14
Project: mao-android   File: DsFragment.java   Source Code and License 6 votes vote down vote up
void traverse(Node root) {
    Queue<Node> layer = new LinkedList<>();
    layer.offer(root);
    while (!layer.isEmpty()) {
        Queue<Node> nextLayer = new LinkedList<>();
        Node node = layer.poll();
        while (node != null) {
            System.out.println(node.name);
            if (node.left != null) {
                nextLayer.offer(node.left);
            }
            if (node.right != null) {
                nextLayer.offer(node.right);
            }
            node = layer.poll();
        }
        layer = nextLayer;
    }
}
 
Example 15
Project: unitimes   File: CurriculaCourseDemands.java   Source Code and License 6 votes vote down vote up
protected void computeTargetShare(int nrStudents, Collection<CurriculumCourse> courses, CurriculumCourseGroupsProvider course2groups, CurModel model) {
	for (CurriculumCourse c1: courses) {
		float x1 = c1.getPercShare() * nrStudents;
		Set<CurriculumCourse>[] group = new HashSet[] { new HashSet<CurriculumCourse>(), new HashSet<CurriculumCourse>()};
		Queue<CurriculumCourse> queue = new LinkedList<CurriculumCourse>();
		queue.add(c1);
		Set<CurriculumCourseGroup> done = new HashSet<CurriculumCourseGroup>();
		while (!queue.isEmpty()) {
			CurriculumCourse c = queue.poll();
			for (CurriculumCourseGroup g: course2groups.getGroups(c))
				if (done.add(g))
					for (CurriculumCourse x: courses)
						if (!x.equals(c) && !x.equals(c1) && course2groups.getGroups(x).contains(g) && group[group[0].contains(c) ? 0 : g.getType()].add(x))
							queue.add(x);
		}
		for (CurriculumCourse c2: courses) {
			float x2 = c2.getPercShare() * nrStudents;
			if (c1.getUniqueId() >= c2.getUniqueId()) continue;
			float share = c1.getPercShare() * c2.getPercShare() * nrStudents;
			boolean opt = group[0].contains(c2);
			boolean req = !opt && group[1].contains(c2);
			model.setTargetShare(c1.getUniqueId(), c2.getUniqueId(), opt ? 0.0 : req ? Math.min(x1, x2) : share, true);
		}
	}
}
 
Example 16
Project: hadoop-oss   File: DirectBufferPool.java   Source Code and License 6 votes vote down vote up
/**
 * Allocate a direct buffer of the specified size, in bytes.
 * If a pooled buffer is available, returns that. Otherwise
 * allocates a new one.
 */
public ByteBuffer getBuffer(int size) {
  Queue<WeakReference<ByteBuffer>> list = buffersBySize.get(size);
  if (list == null) {
    // no available buffers for this size
    return ByteBuffer.allocateDirect(size);
  }
  
  WeakReference<ByteBuffer> ref;
  while ((ref = list.poll()) != null) {
    ByteBuffer b = ref.get();
    if (b != null) {
      return b;
    }
  }

  return ByteBuffer.allocateDirect(size);
}
 
Example 17
Project: BestPracticeApp   File: N23_PrintBinaryTree.java   Source Code and License 6 votes vote down vote up
private static void print(Tree tree) {
    Queue<Tree.Node> queue = new LinkedList<>();
    Tree.Node root = tree.root;

    queue.add(root);
    while (!queue.isEmpty()) {
        Tree.Node poll = queue.poll();
        if (poll.left != null) {
            queue.add(poll.left);
        }
        if (poll.right != null) {
            queue.add(poll.right);
        }

        System.out.println(poll.value);

    }

}
 
Example 18
Project: APacheSynapseSimplePOC   File: CommonsCollections2.java   Source Code and License 6 votes vote down vote up
public Queue<Object> getObject(final String command) throws Exception {
	final Object templates = Gadgets.createTemplatesImpl(command);
	// mock method name until armed
	final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);

	// create queue with numbers and basic comparator
	final PriorityQueue<Object> queue = new PriorityQueue<Object>(2,new TransformingComparator(transformer));
	// stub data for replacement later
	queue.add(1);
	queue.add(1);

	// switch method called by comparator
	Reflections.setFieldValue(transformer, "iMethodName", "newTransformer");

	// switch contents of queue
	final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
	queueArray[0] = templates;
	queueArray[1] = 1;

	return queue;
}
 
Example 19
Project: twister2   File: MPIDataFlowOperationMemoryMapped.java   Source Code and License 6 votes vote down vote up
/**
 * Setup the receives and send sendBuffers
 */
protected void setupCommunication() {
  // we will receive from these
  int maxReceiveBuffers = MPIContext.receiveBufferCount(config);
  int receiveBufferSize = MPIContext.bufferSize(config);
  for (Integer recv : receivingExecutors) {
    Queue<MPIBuffer> recvList = new LinkedList<>();
    for (int i = 0; i < maxReceiveBuffers; i++) {
      recvList.add(new MPIBuffer(receiveBufferSize));
    }
    // register with the channel
    LOG.info(instancePlan.getThisExecutor() + " Register to receive from: " + recv);
    channel.receiveMessage(recv, edge, this, recvList);
    receiveBuffers.put(recv, recvList);
  }

  // configure the send sendBuffers
  int sendBufferSize = MPIContext.bufferSize(config);
  int sendBufferCount = MPIContext.sendBuffersCount(config);
  for (int i = 0; i < sendBufferCount; i++) {
    MPIBuffer buffer = new MPIBuffer(sendBufferSize);
    sendBuffers.offer(buffer);
  }
}
 
Example 20
Project: marshalsec   File: JDKUtil.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings ( {
    "rawtypes", "unchecked"
} )
public static Queue<Object> makePriorityQueue ( Object tgt, Comparator comparator ) throws Exception {
    // create queue with numbers and basic comparator
    final PriorityQueue<Object> queue = new PriorityQueue<>(2, comparator);
    // stub data for replacement later
    queue.add(new BigInteger("1"));
    queue.add(new BigInteger("1"));

    // switch contents of queue
    final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
    queueArray[ 0 ] = tgt;
    queueArray[ 1 ] = tgt;

    return queue;
}
 
Example 21
Project: smile_1.5.0_java7   File: AdjacencyList.java   Source Code and License 6 votes vote down vote up
/**
 * Breadth-first search of graph.
 * @param v the start vertex.
 * @param cc the array to store the connected component id of vertices.
 * @param id the current component id.
 */
private void bfs(Visitor visitor, int v, int[] cc, int id) {
    visitor.visit(v);
    cc[v] = id;
    Queue<Integer> queue = new LinkedList<>();
    queue.offer(v);
    while (!queue.isEmpty()) {
        int t = queue.poll();
        for (Edge edge : graph[t]) {
            int i = edge.v2;
            if (!digraph && i == t) {
                i = edge.v1;
            }

            if (cc[i] == -1) {
                visitor.visit(i);
                queue.offer(i);
                cc[i] = id;
            }
        }
    }
}
 
Example 22
Project: spark-dependencies   File: TreeGenerator.java   Source Code and License 6 votes vote down vote up
private void generateDescendants(Queue<Node> queue, int numOfNodes, final int maxNumberOfDescendants) {
  if (numOfNodes <= 0) {
    return;
  }

  Node parent = queue.poll();
  if (parent == null) {
    return;
  }
  for (int i = 0; i < maxNumberOfDescendants; i++) {
    Node descendant = new Node(tracers.get(tracersRandom.nextInt(tracers.size())).tracingWrapper(), parent);
    queue.add(descendant);
    if (--numOfNodes <= 0) {
      return;
    }
  }
  generateDescendants(queue, numOfNodes, maxNumberOfDescendants);
}
 
Example 23
Project: boohee_v5.6   File: OperatorGroupBy.java   Source Code and License 6 votes vote down vote up
private void emitItem(GroupState<K, T> groupState, Object item) {
    Queue<Object> q = groupState.buffer;
    AtomicLong keyRequested = groupState.requested;
    REQUESTED.decrementAndGet(this);
    if (keyRequested == null || keyRequested.get() <= 0 || !(q == null || q.isEmpty())) {
        q.add(item);
        BUFFERED_COUNT.incrementAndGet(this);
        if (groupState.count.getAndIncrement() == 0) {
            pollQueue(groupState);
        }
    } else {
        nl.accept(groupState.getObserver(), item);
        if (keyRequested.get() != Long.MAX_VALUE) {
            keyRequested.decrementAndGet();
        }
    }
    requestMoreIfNecessary();
}
 
Example 24
Project: JavaEvents   File: EventManager.java   Source Code and License 6 votes vote down vote up
public <E> void registerEventWithHandler(Class<E> eventClass, IEventHandler<?> handler){
	synchronized (EVENT_LISTENERS) {
		if(!EVENT_LISTENERS.containsKey(eventClass)){
			EVENT_LISTENERS.put(eventClass, new EventListenerCenter(handler, eventClass));
			synchronized (QUEUED_LISTENERS) {
				if(QUEUED_LISTENERS.containsKey(eventClass)){
					Queue<?> queue = QUEUED_LISTENERS.get(eventClass);
					for (Object object : queue) {
						EVENT_LISTENERS.get(eventClass).add(object);
					}
					QUEUED_LISTENERS.remove(eventClass);
				}	
			}
		}	
	}
}
 
Example 25
Project: JavaEvents   File: EventManager.java   Source Code and License 6 votes vote down vote up
public <L> void registerToInterface(Class<L> interfaceClass, L listener) throws WrongListenerTypeException{
	synchronized (EVENT_THROWERS) {
		if(EVENT_THROWERS.containsKey(interfaceClass)){
			LinkedHashSet<IEventThrower<?>> list = EVENT_THROWERS.get(interfaceClass);
			for (IEventThrower<?> iEventThrower : list) {
				@SuppressWarnings("unchecked")
				IEventThrower<L> thrower = (IEventThrower<L>) iEventThrower;
				try{
					thrower.subscribe(listener);
				}catch(ClassCastException e){
					throw new WrongListenerTypeException();
				}	
			}
		}else{
			if(QUEUED_LISTENERS.containsKey(interfaceClass)){
				QUEUED_LISTENERS.get(interfaceClass).add(listener);
			}else{
				Queue<Object> queue = new ArrayDeque<>();
				queue.add(listener);
				QUEUED_LISTENERS.put(interfaceClass, queue);
			}
		}
	}
}
 
Example 26
Project: apache-tomcat-7.0.73-with-comment   File: TestWebSocketFrameClient.java   Source Code and License 6 votes vote down vote up
public void echoTester(String path) throws Exception {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().build();
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() + path));
    CountDownLatch latch =
            new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    for (String message : messages) {
        Assert.assertEquals("Hello", message);
    }
    wsSession.close();
}
 
Example 27
Project: MalmoAgent   File: MoveTo.java   Source Code and License 5 votes vote down vote up
public void addChild(float x, float z, Observations obs, Map<Position, Position> map, Queue<Position> nextPos, Position currentPosition) {
    if (isFree(x, z, obs)) {
        Position child = new Position(x, z);
        if (!map.containsKey(child)) {
            map.put(child, currentPosition);
            nextPos.add(child);
        }
    }
}
 
Example 28
Project: storm-dynamic-spout   File: DefaultRetryManagerTest.java   Source Code and License 5 votes vote down vote up
private void validateTupleNotInFailedSetButIsInFlight(DefaultRetryManager retryManager, MessageId messageId) {
    // Loop through all failed tuples
    for (Long key : retryManager.getFailedMessageIds().keySet()) {
        Queue queue = retryManager.getFailedMessageIds().get(key);
        assertFalse("Should not contain our messageId", queue.contains(messageId));
    }
    assertTrue("Should be tracked as in flight", retryManager.getRetriesInFlight().contains(messageId));
}
 
Example 29
Project: game-executor   File: BindingUpdateThread.java   Source Code and License 5 votes vote down vote up
public BindingUpdateThread(BindThreadUpdateExecutorService bindThreadUpdateExecutorService, DispatchThread dispatchThread, Queue<IUpdate> iUpdates, BlockingQueue<IUpdate> fetchUpdates) {
    super(dispatchThread, dispatchThread.getEventBus());
    this.bindThreadUpdateExecutorService = bindThreadUpdateExecutorService;
    this.iUpdates = iUpdates;
    this.fetchUpdates = fetchUpdates;
    this.finishList = new ArrayList<IUpdate>();
}
 
Example 30
Project: googles-monorepo-demo   File: TestsForQueuesInJavaUtil.java   Source Code and License 5 votes vote down vote up
public Test testsForArrayBlockingQueue() {
  return QueueTestSuiteBuilder.using(
          new TestStringQueueGenerator() {
            @Override
            public Queue<String> create(String[] elements) {
              return new ArrayBlockingQueue<String>(100, false, MinimalCollection.of(elements));
            }
          })
      .named("ArrayBlockingQueue")
      .withFeatures(
          CollectionFeature.GENERAL_PURPOSE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY)
      .suppressing(suppressForArrayBlockingQueue())
      .createTestSuite();
}
 
Example 31
Project: Fatigue-Detection   File: GPUImageRenderer.java   Source Code and License 5 votes vote down vote up
void runAll(Queue<CmdItem> queue) {
    synchronized (queue) {
        while (!queue.isEmpty()) {
            CmdItem cmdItem = queue.poll();

            switch (cmdItem.cmdId) {
                case CMD_PROCESS_FRAME:
                    processFrame((byte[]) cmdItem.param1, (Camera) cmdItem.param2);
                    break;
                case CMD_SETUP_SURFACE_TEXTURE:
                    setUpSurfaceTextureInternal((Camera) cmdItem.param1, (byte[]) cmdItem.param2);
                    break;
                case CMD_SET_FILTER:
                    setFilterInternal((GPUImageFilterGroupBase) cmdItem.param1);
                    break;
                case CMD_RERUN_ONDRAW_RUNNABLE:
                    ((Runnable) cmdItem.param1).run();
                    break;
                case CMD_RERUN_DRAWEND_RUNNABLE:
                    ((Runnable) cmdItem.param1).run();
                    break;
                default:
                    throw new RuntimeException("can't find command");
            }

            cmdItem.param1 = cmdItem.param2 = null;
            mCmdItemCacher.cache(cmdItem);
        }
    }
}
 
Example 32
Project: class-code   File: BinaryTree.java   Source Code and License 5 votes vote down vote up
public void bfTraverse() {
	Queue<Node> q = new LinkedList<Node>();
	q.add(r);
	while (!q.isEmpty()) {
		Node u = q.remove();
		if (u.left != nil) q.add(u.left);
		if (u.right != nil) q.add(u.right);
	}
}
 
Example 33
Project: monarch   File: PartitionedRegionQueryEvaluatorTest.java   Source Code and License 5 votes vote down vote up
public ExtendedPartitionedRegionQueryEvaluator(InternalDistributedSystem sys,
    PartitionedRegion pr, DefaultQuery query, Object[] parameters,
    SelectResults cumulativeResults, Set<Integer> bucketsToQuery,
    Queue<PartitionedQueryScenario> scenarios) {
  super(sys, pr, query, parameters, cumulativeResults, bucketsToQuery);
  this.scenarios = scenarios;
  extendedPRQueryProcessor =
      new ExtendedPRQueryProcessor(pr, query, null, new LinkedList(bucketsToQuery));
}
 
Example 34
Project: kheera-testrunner-android   File: Parser.java   Source Code and License 5 votes vote down vote up
private boolean lookahead_0(ParserContext context, Token currentToken) {
    currentToken.detach();
    Token token;
    Queue<Token> queue = new ArrayDeque<Token>();
    boolean match = false;
    do
    {
        token = readToken(context);
        token.detach();
        queue.add(token);

        if (false
            || match_ExamplesLine(context, token)
        )
        {
            match = true;
            break;
        }
    } while (false
        || match_Empty(context, token)
        || match_Comment(context, token)
        || match_TagLine(context, token)
    );

    context.tokenQueue.addAll(queue);

    return match;
}
 
Example 35
Project: GitHub   File: RequestQueue.java   Source Code and License 5 votes vote down vote up
/**
 * Called from {@link Request#finish(String)}, indicating that processing of the given request
 * has finished.
 *
 * <p>Releases waiting requests for <code>request.getCacheKey()</code> if
 *      <code>request.shouldCache()</code>.</p>
 */
<T> void finish(Request<T> request) {
    // Remove from the set of requests currently being processed.
    synchronized (mCurrentRequests) {
        mCurrentRequests.remove(request);
    }
    synchronized (mFinishedListeners) {
      for (RequestFinishedListener<T> listener : mFinishedListeners) {
        listener.onRequestFinished(request);
      }
    }

    if (request.shouldCache()) {
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey);
            if (waitingRequests != null) {
                if (VolleyLog.DEBUG) {
                    VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.",
                            waitingRequests.size(), cacheKey);
                }
                // Process all queued up requests. They won't be considered as in flight, but
                // that's not a problem as the cache has been primed by 'request'.
                mCacheQueue.addAll(waitingRequests);
            }
        }
    }
}
 
Example 36
Project: Java-9-Programming-Blueprints   File: DateCalcExpressionParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void nowWithoutSpacesAndTime() {
    Queue<Token> words = parser.parse("now+03:04");
    Assert.assertTrue(words.poll() instanceof TimeToken);
    Assert.assertTrue(words.poll() instanceof OperatorToken);
    Assert.assertTrue(words.poll() instanceof TimeToken);
}
 
Example 37
Project: GitHub   File: FunGameBattleCityHeader.java   Source Code and License 5 votes vote down vote up
/**
 * 绘制三条轨道上的敌方坦克
 * @param canvas 默认画布
 */
private void drawEnemyTank(Canvas canvas, int width) {
    mPaint.setColor(lModelColor);
    offsetETankX += enemySpeed;
    if (offsetETankX / enemyTankSpace == 1 || once) {
        offsetETankX = 0;
        once = false;
    }

    boolean isOverstep = false;
    int option = apperanceOption();
    for (int i = 0; i < TANK_ROW_NUM; i++) {
        Queue<RectF> rectFQueue = eTankSparseArray.get(i);

        if (offsetETankX == 0 && i == option) {
            rectFQueue.offer(generateEnemyTank(i));
        }

        for (RectF rectF : rectFQueue) {
            if (rectF.left >= width) {
                isOverstep = true;
                if (++overstepNum >= DEFAULT_TANK_MAGIC_TOTAL_NUM) {
                    status = STATUS_GAME_OVER;
                    break;
                }
                continue;
            }
            drawTank(canvas, rectF);
        }

        if (status == STATUS_GAME_OVER) break;
        if (isOverstep) {
            rectFQueue.poll();
            isOverstep = false;
        }
    }
    invalidate();
}
 
Example 38
Project: openjdk-jdk10   File: ConcurrentLinkedDequeTest.java   Source Code and License 5 votes vote down vote up
/**
 * A deserialized/reserialized deque has same elements in same order
 */
public void testSerialization() throws Exception {
    Queue x = populatedDeque(SIZE);
    Queue y = serialClone(x);

    assertNotSame(x, y);
    assertEquals(x.size(), y.size());
    assertEquals(x.toString(), y.toString());
    assertTrue(Arrays.equals(x.toArray(), y.toArray()));
    while (!x.isEmpty()) {
        assertFalse(y.isEmpty());
        assertEquals(x.remove(), y.remove());
    }
    assertTrue(y.isEmpty());
}
 
Example 39
Project: Nird2   File: ValidationManagerImpl.java   Source Code and License 5 votes vote down vote up
@DatabaseExecutor
private Queue<MessageId> getPendingDependents(Transaction txn, MessageId m)
		throws DbException {
	Queue<MessageId> pending = new LinkedList<MessageId>();
	Map<MessageId, State> states = db.getMessageDependents(txn, m);
	for (Entry<MessageId, State> e : states.entrySet()) {
		if (e.getValue() == PENDING) pending.add(e.getKey());
	}
	return pending;
}
 
Example 40
Project: voogasalad-ltub   File: PathCreator.java   Source Code and License 5 votes vote down vote up
private void targetSetOnMouseDragged(ScreenMap target, MouseEvent e, Queue<GamePoint> newPath) {
	Point2D point = target.sceneToLocal(e.getSceneX(), e.getSceneY());
	double mouseX = point.getX();
	double mouseY = point.getY();
	GamePoint coords = target.getCoordOfMouseHover(mouseX, mouseY);
	GamePoint actualGameLocation = target.getActualLocationOfSprite(coords);
	if (!coordAlreadyInPath(actualGameLocation, newPath)) {
		newPath.add(actualGameLocation);
		target.addBorderToCoordinate(coords);
	}
	
	e.consume();
}
 
Example 41
Project: openjdk-jdk10   File: ConcurrentQueueLoops.java   Source Code and License 5 votes vote down vote up
void test(String[] args) throws Throwable {
    if (args.length > 0)
        maxStages = Integer.parseInt(args[0]);
    if (args.length > 1)
        items = Integer.parseInt(args[1]);

    for (Queue<Integer> queue : concurrentQueues())
        test(queue);
}
 
Example 42
Project: practice-coding   File: BinaryTreeLevelOrderTraversal.java   Source Code and License 5 votes vote down vote up
private List<List<Integer>> getLevelOrderTraversal(Node root) {
    List<List<Integer>> result = new ArrayList<>();

    if (root == null) {
        return result;
    }

    Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    List<Integer> temp = Arrays.asList(root.val);
    result.add(temp);
    while (!queue.isEmpty()) {
        Queue<Node> currentLevel = new LinkedList<>();
        List<Integer> subResult = new ArrayList<>();

        while (!queue.isEmpty()) {
            Node currNodel = queue.poll();
            if (currNodel.left != null) {
                currentLevel.add(currNodel.left);
                subResult.add(currNodel.left.val);
            }
            if (currNodel.right != null) {
                currentLevel.add(currNodel.right);
                subResult.add(currNodel.right.val);
            }

        }
        if (!subResult.isEmpty()) {
            result.add(subResult);
        }
        queue = currentLevel;
    }

    return result;

}
 
Example 43
Project: TSBW4J   File: CommandCenterConstruction.java   Source Code and License 5 votes vote down vote up
@Override
public TilePosition getBuildTile(UnitInventory unitInventory, MapAnalyzer mapAnalyzer, SCV builder, Queue<Project> projects) {
	
	TilePosition buildTile = null;
	
	TilePosition mainPosition;
	if (unitInventory.getMain() != null) {
		mainPosition = unitInventory.getMain().getTilePosition();
	} else {
		mainPosition = this.startLocation;
	}
	
	List<TilePosition> baseLocations = mapAnalyzer.getBaseLocationsAsPosition();
	
	double distance = Double.MAX_VALUE;
	for (TilePosition currentPosition : baseLocations) {
		
		if (mapAnalyzer.getBWMap().canBuildHere(currentPosition, super.getUnitType())  && !collidesWithConstruction(currentPosition, this.unitType, projects) 
				&& !this.startLocation.equals(currentPosition)) {
			
			double currentDistance = mapAnalyzer.getGroundDistance(mainPosition, currentPosition);
			if (currentDistance < distance) {
				buildTile = currentPosition;
				distance = currentDistance;
			}
		}
	} 
	return buildTile;
}
 
Example 44
Project: googles-monorepo-demo   File: Iterables.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a view of the supplied iterable that wraps each generated
 * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}.
 *
 * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will
 * get entries from {@link Queue#remove()} since {@link Queue}'s iteration
 * order is undefined.  Calling {@link Iterator#hasNext()} on a generated
 * iterator from the returned iterable may cause an item to be immediately
 * dequeued for return on a subsequent call to {@link Iterator#next()}.
 *
 * @param iterable the iterable to wrap
 * @return a view of the supplied iterable that wraps each generated iterator
 *     through {@link Iterators#consumingIterator(Iterator)}; for queues,
 *     an iterable that generates iterators that return and consume the
 *     queue's elements in queue order
 *
 * @see Iterators#consumingIterator(Iterator)
 * @since 2.0
 */
public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
  if (iterable instanceof Queue) {
    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return new ConsumingQueueIterator<T>((Queue<T>) iterable);
      }

      @Override
      public String toString() {
        return "Iterables.consumingIterable(...)";
      }
    };
  }

  checkNotNull(iterable);

  return new FluentIterable<T>() {
    @Override
    public Iterator<T> iterator() {
      return Iterators.consumingIterator(iterable.iterator());
    }

    @Override
    public String toString() {
      return "Iterables.consumingIterable(...)";
    }
  };
}
 
Example 45
Project: openjdk-jdk10   File: LinkedBlockingDequeTest.java   Source Code and License 5 votes vote down vote up
/**
 * A deserialized/reserialized deque has same elements in same order
 */
public void testSerialization() throws Exception {
    Queue x = populatedDeque(SIZE);
    Queue y = serialClone(x);

    assertNotSame(y, x);
    assertEquals(x.size(), y.size());
    assertEquals(x.toString(), y.toString());
    assertTrue(Arrays.equals(x.toArray(), y.toArray()));
    while (!x.isEmpty()) {
        assertFalse(y.isEmpty());
        assertEquals(x.remove(), y.remove());
    }
    assertTrue(y.isEmpty());
}
 
Example 46
Project: OpenJSharp   File: PolicyModelTranslator.java   Source Code and License 5 votes vote down vote up
/**
 * Decomposes the unprocessed alternative content into two different collections:
 * <p/>
 * Content of 'EXACTLY_ONE' child nodes is expanded and placed in one list and
 * 'ASSERTION' nodes are placed into other list. Direct 'ALL' and 'POLICY' child nodes are 'dissolved' in the process.
 *
 * Method reuses precreated ContentDecomposition object, which is reset before reuse.
 */
private void decompose(final Collection<ModelNode> content, final ContentDecomposition decomposition) throws PolicyException {
    decomposition.reset();

    final Queue<ModelNode> allContentQueue = new LinkedList<ModelNode>(content);
    ModelNode node;
    while ((node = allContentQueue.poll()) != null) {
        // dissolving direct 'POLICY', 'POLICY_REFERENCE' and 'ALL' child nodes
        switch (node.getType()) {
            case POLICY :
            case ALL :
                allContentQueue.addAll(node.getChildren());
                break;
            case POLICY_REFERENCE :
                allContentQueue.addAll(getReferencedModelRootNode(node).getChildren());
                break;
            case EXACTLY_ONE :
                decomposition.exactlyOneContents.add(expandsExactlyOneContent(node.getChildren()));
                break;
            case ASSERTION :
                decomposition.assertions.add(node);
                break;
            default :
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0007_UNEXPECTED_MODEL_NODE_TYPE_FOUND(node.getType())));
        }
    }
}
 
Example 47
Project: the-one-mdonnyk   File: ActivenessHandler.java   Source Code and License 5 votes vote down vote up
private Queue<TimeRange> parseActiveTimes(Settings s) {
	double [] times;
	String sName = s.getFullPropertyName(ACTIVE_TIMES_S);
	
	if (s.contains(ACTIVE_TIMES_S)) {
		times = s.getCsvDoubles(ACTIVE_TIMES_S);
		if (times.length % 2 != 0) {
			throw new SettingsError("Invalid amount of values (" + 
					times.length + ") for setting " + sName + ". Must " + 
					"be divisable by 2");
		}
	}
	else {
		return null; // no setting -> always active
	}

	Queue<TimeRange> timesList = new LinkedList<TimeRange>(); 
	
	for (int i=0; i<times.length; i+= 2) {
		double start = times[i];
		double end = times[i+1];
		
		if (start > end) {
			throw new SettingsError("Start time (" + start + ") is " + 
					" bigger than end time (" + end + ") in setting " + 
					sName);
		}
		
		timesList.add(new TimeRange(start, end));
	}
	
	return timesList;
}
 
Example 48
Project: kourami   File: HLAGraph.java   Source Code and License 5 votes vote down vote up
public ArrayList<Path> findAllSTPath(Node s, Node t){
int bubbleSize = t.getColIndex() - s.getColIndex() + 1;
int endColumnIndex = t.getColIndex();
ArrayList<Path> results = new ArrayList<Path>();
Queue<Path> pathsQ = new LinkedList<Path>();
//Set<CustomeWeightedEdge> edges = this.g.outgoingEdgesOf(s);
Iterator<CustomWeightedEdge> itr = this.g.outgoingEdgesOf(s).iterator();
//first load all outing edges as paths in paths queue.
while(itr.hasNext()){
    pathsQ.add(new Path(itr.next()));
}
Path firstPath = null;
//while we have paths to explore further in the queue
while((firstPath = pathsQ.poll())!=null){
    //obtain the vertex at the end for this path
    Node lastVertex = firstPath.getLastVertex(this.g);
    //if the last vertex is t, then we add this path in the result
    if(lastVertex.equals(t)){
	if(firstPath.getOrderedEdgeList().size() == (bubbleSize -1))
	    results.add(firstPath);
	else{
	    if(HLA.DEBUG){
		HLA.log.appendln("IGNORING PATH (WRONG LENGTH)");
		firstPath.printInfo();
	    }
	}
    }else{//otherwise, we need to explor the paths further ONLY IF current columnIndex is less than destination col INDEX
	if(lastVertex.getColIndex() < endColumnIndex){
	    itr = this.g.outgoingEdgesOf(lastVertex).iterator();
	    while(itr.hasNext()){
		Path tmpP = firstPath.deepCopy();
		tmpP.appendEdge(itr.next());
		pathsQ.add(tmpP);
	    }
	}
    }
}
return results;
   }
 
Example 49
Project: Nird2   File: ValidationManagerImpl.java   Source Code and License 5 votes vote down vote up
private void invalidateNextMessageAsync(final Queue<MessageId> invalidate) {
	if (invalidate.isEmpty()) return;
	dbExecutor.execute(new Runnable() {
		@Override
		public void run() {
			invalidateNextMessage(invalidate);
		}
	});
}
 
Example 50
Project: Big-Number-Calculation   File: ParsingTree.java   Source Code and License 5 votes vote down vote up
public ParsingTree(String expression) {
	tokenCount = 0;
	tokenMap = new HashMap<String, String>();
	expression = expression.trim().replace(" ", "");
	//System.out.println("expression:" + expression);
	String tokenizedExp = tokenize(expression);
	//System.out.println("tokenized expression:" + tokenizedExp);
	//System.out.println(infixToPostfix(tokenizedExp));
	String prefix = infixToPrefix(tokenizedExp);
	//System.out.println("Queue:" + prefix);
	Queue<String> queue = prefixToQueue(prefix);
	buildTree(queue);
	
}
 
Example 51
Project: openjdk-jdk10   File: WhiteBox.java   Source Code and License 5 votes vote down vote up
void checkIterationSanity(Queue q) {
    if (rnd.nextBoolean())
        return;
    int size = q.size();
    Object[] a = q.toArray();
    Object[] b = new Object[size+2];
    Arrays.fill(b, Boolean.TRUE);
    Object[] c = q.toArray(b);
    assertEquals(a.length, size);
    assertSame(b, c);
    assertNull(b[size]);
    assertSame(b[size+1], Boolean.TRUE);
    assertEquals(q.toString(), Arrays.toString(a));
    Integer[] xx = null, yy = null;
    if (size > 0) {
        xx = new Integer[size - 1];
        Arrays.fill(xx, 42);
        yy = ((Queue<Integer>)q).toArray(xx);
        for (Integer zz : xx)
            assertEquals(42, (int) zz);
    }
    Iterator it = q.iterator();
    for (int i = 0; i < size; i++) {
        if (rnd.nextBoolean()) assertTrue(it.hasNext());
        Object x = it.next();
        assertSame(x, a[i]);
        assertSame(x, b[i]);
        if (xx != null) assertSame(x, yy[i]);
    }
    if (rnd.nextBoolean()) assertTrue(!it.hasNext());
}
 
Example 52
Project: SparkSeq   File: FrequencyTable.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a code tree that is optimal for the symbol frequencies in this table.
 * The tree always contains at least 2 leaves (even if they come from symbols with
 * 0 frequency), to avoid degenerate trees. Note that optimal trees are not unique.
 * @return an optimal code tree for this frequency table
 */
public CodeTree buildCodeTree() {
	// Note that if two nodes have the same frequency, then the tie is broken
	// by which tree contains the lowest symbol. Thus the algorithm has a
	// deterministic output and does not rely on the queue to break ties.
	Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>();
	
	// Add leaves for symbols with non-zero frequency
	for (int i = 0; i < frequencies.length; i++) {
		if (frequencies[i] > 0)
			pqueue.add(new NodeWithFrequency(new Leaf(i), i, frequencies[i]));
	}
	
	// Pad with zero-frequency symbols until queue has at least 2 items
	for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) {
		if (frequencies[i] == 0)
			pqueue.add(new NodeWithFrequency(new Leaf(i), i, 0));
	}
	if (pqueue.size() < 2)
		throw new AssertionError();
	
	// Repeatedly tie together two nodes with the lowest frequency
	while (pqueue.size() > 1) {
		NodeWithFrequency x = pqueue.remove();
		NodeWithFrequency y = pqueue.remove();
		pqueue.add(new NodeWithFrequency(
			new InternalNode(x.node, y.node),
			Math.min(x.lowestSymbol, y.lowestSymbol),
			x.frequency + y.frequency));
	}
	
	// Return the remaining node
	return new CodeTree((InternalNode)pqueue.remove().node, frequencies.length);
}
 
Example 53
Project: test-as-you-think   File: Functions.java   Source Code and License 5 votes vote down vote up
static <$Target, $Argument1, $Argument2, $Argument3, $Result> CheckedTriFunction<$Target, $Argument1,
        $Argument2, $Result> toTriFunction(
        CheckedQuadriFunction<$Target, $Argument1, $Argument2, $Argument3, $Result> quadriFunction,
        Queue<Supplier> arguments) {
    return (target, argument1, argument2) -> quadriFunction.apply(target, argument1, argument2,
            ($Argument3) arguments
                    .remove()
                    .get());
}
 
Example 54
Project: navigator   File: MessageQueue.java   Source Code and License 5 votes vote down vote up
public void pushMessageTo(Key recipient, Object message) {
    Queue<Object> messageQueue = messages.get(recipient);
    if(messageQueue == null) {
        messageQueue = new ConcurrentLinkedQueue<>();
        messages.put(recipient, messageQueue);
    }
    messageQueue.add(message);
}
 
Example 55
Project: code-sentinel   File: TSTest.java   Source Code and License 5 votes vote down vote up
public void testIntentionOrder() {
    Intention i1 = new Intention();
    Intention i2 = new Intention(); 
    
    Intention i3 = new Intention(); 
    i3.setAtomic(1);
    assertTrue(i3.isAtomic());
    
    Intention i4 = new Intention();
    
    Queue<Intention> q1 = new PriorityQueue<Intention>();
    q1.offer(i1);
    q1.offer(i2);
    q1.offer(i3);
    q1.offer(i4);
    assertEquals(q1.poll().getId(), i3.getId());
    //System.out.println(q1.poll());
    //System.out.println(q1.poll());
    //System.out.println(q1.poll());

    /*
    List<Intention> l = new ArrayList<Intention>();
    l.add(i1);
    l.add(i2);
    l.add(i3);
    l.add(i4);
    Collections.sort(l);
    
    System.out.println(l);
    */
    
}
 
Example 56
Project: candlelight   File: DungeonHandler.java   Source Code and License 5 votes vote down vote up
private void solveSubRegionNeighbor(Vector2fc pos, Queue<Vector2fc> opened, Set<Vector2fc> closed, int region)
{
	if (!closed.contains(pos) && !this.dungeon.isSolid(pos.x(), pos.y()))
	{
		if (!this.dungeon.isPermeable(pos.x(), pos.y()))
		{
			opened.offer(new Vector2f(pos));
		}
		else
		{
			this.dungeon.setRegion(pos.x(), pos.y(), region);
		}
	}
}
 
Example 57
Project: openjdk-jdk10   File: MC.java   Source Code and License 5 votes vote down vote up
/**
 * Writes out the exceptions themselves.
 *
 * @param groupName the name of this group of exceptions.
 * @param exceptions the exceptions to write out.
 * @param className the name of the generated class.
 * @param pw the {@link IndentingPrintWriter} for writing to the file.
 */
private void writeExceptions(String groupName, Queue<InputException> exceptions,
                             String className, IndentingPrintWriter pw) {
  for (InputException e : exceptions) {
    pw.println("///////////////////////////////////////////////////////////");
    pw.printMsg("// @", e.getName());
    pw.println("///////////////////////////////////////////////////////////");
    pw.println();
    for (InputCode c : e.getCodes())
      writeMethods(groupName, e.getName(), c.getName(), c.getCode(),
                   c.getLogLevel(), className, StringUtil.countArgs(c.getMessage()), pw);
    pw.flush();
  }
}
 
Example 58
Project: RxJava3-preview   File: QueueDrainHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Accumulates requests (not validated) and handles the completed mode draining of the queue based on the requests.
 *
 * <p>
 * Post-completion backpressure handles the case when a source produces values based on
 * requests when it is active but more values are available even after its completion.
 * In this case, the onComplete() can't just emit the contents of the queue but has to
 * coordinate with the requested amounts. This requires two distinct modes: active and
 * completed. In active mode, requests flow through and the queue is not accessed but
 * in completed mode, requests no-longer reach the upstream but help in draining the queue.
 *
 * @param <T> the value type emitted
 * @param n the request amount, positive (not validated)
 * @param actual the target Subscriber to send events to
 * @param queue the queue to drain if in the post-complete state
 * @param state holds the request amount and the post-completed flag
 * @param isCancelled a supplier that returns true if the drain has been cancelled
 * @return true if the state indicates a completion state.
 */
public static <T> boolean postCompleteRequest(long n,
                                              Subscriber<? super T> actual,
                                              Queue<T> queue,
                                              AtomicLong state,
                                              BooleanSupplier isCancelled) {
    for (; ; ) {
        long r = state.get();

        // extract the current request amount
        long r0 = r & REQUESTED_MASK;

        // preserve COMPLETED_MASK and calculate new requested amount
        long u = (r & COMPLETED_MASK) | BackpressureHelper.addCap(r0, n);

        if (state.compareAndSet(r, u)) {
            // (complete, 0) -> (complete, n) transition then replay
            if (r == COMPLETED_MASK) {

                postCompleteDrain(n | COMPLETED_MASK, actual, queue, state, isCancelled);

                return true;
            }
            // (active, r) -> (active, r + n) transition then continue with requesting from upstream
            return false;
        }
    }

}
 
Example 59
Project: incubator-netbeans   File: ProfileSupportTest.java   Source Code and License 5 votes vote down vote up
private void collectClassFiles(@NonNull final File folder, @NonNull final Queue<? super URL> q) throws MalformedURLException {
    final File[] chld = folder.listFiles();
    if (chld == null) {
        return;
    }
    for (File f : chld) {
        if (f.isDirectory()) {
            collectClassFiles(f, q);
        } else if (FileObjects.CLASS.equals(FileObjects.getExtension(f.getName()))) {
            q.offer(Utilities.toURL(f));
        }
    }
}
 
Example 60
Project: ditb   File: HRegion.java   Source Code and License 5 votes vote down vote up
private Queue<byte[]> generateLMDIndexCandidateRows(Scan scan) throws IOException {
  List<byte[]> list = new ArrayList<>();
  for (Map.Entry<byte[], NavigableSet<byte[]>> entry : scan.getFamilyMap().entrySet()) {
    // memstore
    HStore store = (HStore) stores.get(entry.getKey());
    InternalScan internalScan = new InternalScan(scan);
    internalScan.setCacheBlocks(false);
    internalScan.setAttribute(IndexConstants.SCAN_WITH_INDEX, null);
    internalScan.checkOnlyMemStore();
    RegionScanner memScanner =
        store.getHRegion().new RegionScannerImpl(internalScan, null, store.getHRegion());
    // store files
    Collection<StoreFile> storeFiles = store.getStoreFilesToScan(scan);
    List<LMDIndexDirectStoreFileScanner> scanners = new ArrayList<>(storeFiles.size());
    for (StoreFile sf : storeFiles) {
      System.out.println("viewing StoreFile :" + sf);
      scanners.add(
          new LMDIndexDirectStoreFileScanner(sf, false, false, false, false, null, readPt, true,
              indexTableRelation.getIndexFamilyMap(),
              ScanRange.ScanRangeList.getScanRangeList(scan), store.getFileSystem(),
              store.cacheConf, conf, true));
    }
    LMDIndexSecondaryStoreScanner secondary =
        new LMDIndexSecondaryStoreScanner(memScanner, scanners);
    list.addAll(secondary.getRowkeys());
    memScanner.close();
  }
  Collections.sort(list, Bytes.BYTES_COMPARATOR);
  Queue<byte[]> ret = new LinkedList<>(list);
  return ret;
}