java.util.Queue Java Examples

The following examples show how to use java.util.Queue. 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: McParkTakeStrategy.java    From JCTools with Apache License 2.0 6 votes vote down vote up
@Override
public E waitPoll(Queue<E> q) throws InterruptedException
{
    E e = q.poll();
    if (e != null)
    {
        return e;
    }

    WAITERS_UPDATER.incrementAndGet(this);
    synchronized (obj)
    {
        while ((e = q.poll()) == null)
        {
            obj.wait();
        }
        WAITERS_UPDATER.decrementAndGet(this);
    }

    return e;
}
 
Example #2
Source File: DefaultPojoClassLookupService.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public List<PojoClass> getPojoClassesRecursively(final String packageName, final PojoClassFilter pojoClassFilter) {
  final List<PojoClass> pojoClasses = new LinkedList<PojoClass>();
  final PojoClassFilter finalFilterChain = getFinalFilterChain(pojoClassFilter);

  final PojoPackage pojoPackage = PojoPackageFactory.getPojoPackage(packageName);

  Queue<PojoPackage> pending = new ConcurrentLinkedQueue<PojoPackage>();
  pending.add(pojoPackage);

  while (!pending.isEmpty()) {
    final PojoPackage entry = pending.remove();
    pending.addAll(entry.getPojoSubPackages());
    pojoClasses.addAll(entry.getPojoClasses(finalFilterChain));
  }
  return pojoClasses;
}
 
Example #3
Source File: Solution.java    From codekata with MIT License 6 votes vote down vote up
public List<Double> averageOfLevels(TreeNode root) {
    ArrayList<Double> result = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        double sum = 0;
        for (int i = 0; i < size; i++) {
            TreeNode tmp = queue.poll();
            sum += (double) tmp.val;
            if (tmp.left != null) queue.add(tmp.left);
            if (tmp.right != null) queue.add(tmp.right);
        }
        result.add(sum / size);
    }
    return result;
}
 
Example #4
Source File: KeyedReceiver.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * Moves all the buffered messages for the given key into the sendQueue and removes the
 * entry in the messages data structure if all the messages are moved
 *
 * @param target target for which the move needs to be done
 * @param messagesPerTarget messages for given target
 * @param key the key to be moved
 * @return true if all the messages for that key are moved successfully
 */
protected boolean moveMessageToSendQueue(int target, Map<Object, Queue<Object>> messagesPerTarget,
                                         Object key) {
  Queue<Object> targetSendQueue = sendQueue.get(target);
  Queue<Object> entryQueue = messagesPerTarget.get(key);
  Object current;

  while ((current = entryQueue.peek()) != null) {
    Tuple send = new Tuple(key, current);

    if (targetSendQueue.offer(send)) {
      entryQueue.poll();
    } else {
      return false;
    }
  }

  if (messagesPerTarget.get(key).isEmpty()) {
    messagesPerTarget.remove(key);
    return true;
  } else {
    return false;
  }
}
 
Example #5
Source File: GCRetention.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
void test(Queue<Boolean> q) {
    long t0 = System.nanoTime();
    for (int i = 0; i < count; i++)
        check(q.add(Boolean.TRUE));
    System.gc();
    System.gc();
    Boolean x;
    while ((x = q.poll()) != null)
        equal(x, Boolean.TRUE);
    check(q.isEmpty());

    for (int i = 0; i < 10 * count; i++) {
        for (int k = 0; k < 3; k++)
            check(q.add(Boolean.TRUE));
        for (int k = 0; k < 3; k++)
            if (q.poll() != Boolean.TRUE)
                fail();
    }
    check(q.isEmpty());

    String className = q.getClass().getSimpleName();
    long elapsed = System.nanoTime() - t0;
    int nanos = (int) ((double) elapsed / (10 * 3 * count));
    results.put(className, String.valueOf(nanos));
}
 
Example #6
Source File: DeepestLeavesSum_1302.java    From AlgoCS with MIT License 6 votes vote down vote up
public int deepestLeavesSum(TreeNode root) {
    if (root == null) return 0;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    int deepLeavesSum = root.val;

    while (!queue.isEmpty()) {
        int len = queue.size();
        deepLeavesSum = 0;
        for (int i = 0; i < len; i++) {
            TreeNode node = queue.poll();
            deepLeavesSum += node.val;
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);
        }
    }

    return deepLeavesSum;
}
 
Example #7
Source File: QueueThroughputBusy.java    From lin-check with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    System.out.println("capacity:" + QUEUE_CAPACITY + " reps:" + REPETITIONS);
    final Queue<Integer> queue = SPSCQueueFactory.createQueue(Integer.parseInt(args[0]), Integer.getInteger("scale", 17));

    final long[] results = new long[20];
    for (int i = 0; i < 20; i++) {
        System.gc();
        results[i] = performanceRun(i, queue);
    }
    // only average last 10 results for summary
    long sum = 0;
    for (int i = 10; i < 20; i++) {
        sum += results[i];
    }
    System.out.format("summary,QueuePerfTest3,%s,%d\n", queue.getClass().getSimpleName(), sum / 10);
}
 
Example #8
Source File: TestOzoneManagerDoubleBufferWithOMResponse.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * This method add's a mix of createBucket/DeleteBucket responses to double
 * buffer. Total number of responses added is specified by bucketCount.
 */
private void doMixTransactions(String volumeName, int bucketCount,
    Queue<OMBucketDeleteResponse> deleteBucketQueue,
    Queue<OMBucketCreateResponse> bucketQueue) {
  for (int i=0; i < bucketCount; i++) {
    String bucketName = UUID.randomUUID().toString();
    long transactionID = trxId.incrementAndGet();
    OMBucketCreateResponse omBucketCreateResponse = createBucket(volumeName,
        bucketName, transactionID);
    // For every 2 transactions have a deleted bucket.
    if (i % 2 == 0) {
      OMBucketDeleteResponse omBucketDeleteResponse =
          (OMBucketDeleteResponse) deleteBucket(volumeName, bucketName,
              trxId.incrementAndGet());
      deleteBucketQueue.add(omBucketDeleteResponse);
    } else {
      bucketQueue.add(omBucketCreateResponse);
    }
  }
}
 
Example #9
Source File: InspectableComponent.java    From litho with Apache License 2.0 6 votes vote down vote up
/** Obtain an instance of a Component nested inside the given inspectable Component. */
@Nullable
public InspectableComponent getNestedInstance(Component component) {
  final Queue<DebugComponent> queue = new LinkedList<>(mComponent.getChildComponents());

  while (!queue.isEmpty()) {
    final DebugComponent childComponent = queue.remove();

    if (childComponent.getComponent() == component) {
      return new InspectableComponent(childComponent);
    }

    queue.addAll(childComponent.getChildComponents());
  }

  return null;
}
 
Example #10
Source File: FluxWindowTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanOverlapSubscriberSmallBuffered() {
 @SuppressWarnings("unchecked")
 Queue<FluxIdentityProcessor<Integer>> mockQueue = Mockito.mock(Queue.class);

    CoreSubscriber<Flux<Integer>> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
    FluxWindow.WindowOverlapSubscriber<Integer> test = new FluxWindow.WindowOverlapSubscriber<Integer>(actual,
            3,3, Queues.unbounded(), mockQueue);

    when(mockQueue.size()).thenReturn(Integer.MAX_VALUE - 2);
    //size() is 1
    test.offer(Processors.unicast());

    assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(Integer.MAX_VALUE - 1);
    assertThat(test.scan(Scannable.Attr.LARGE_BUFFERED)).isEqualTo(Integer.MAX_VALUE - 1L);
}
 
Example #11
Source File: AhoCorasick.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void initialize() {
    //perform bgs to build failure links
    final Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    root.setFailureNode(null);
    while (!queue.isEmpty()) {
        final Node current = queue.poll();
        for (int i = 0; i < 256; i++) {
            final Node next = current.getNeighbor(i);
            if (next != null) {
                //traverse failure to get state
                Node fail = current.getFailureNode();
                while ((fail != null) && fail.getNeighbor(i) == null) {
                    fail = fail.getFailureNode();
                }
                if (fail != null) {
                    next.setFailureNode(fail.getNeighbor(i));
                } else {
                    next.setFailureNode(root);
                }
                queue.add(next);
            }
        }
    }
}
 
Example #12
Source File: ClientConnectionTest.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppendThrows() throws Exception {
    ReplyProcessor processor = new ReplyProcessor(); 
    Flow flow = new Flow(10, 0);
    FlowHandler flowHandler = new FlowHandler("testConnection");
    @Cleanup
    ClientConnection clientConnection = flowHandler.createFlow(flow, processor);
    EmbeddedChannel embeddedChannel = createChannelWithContext(flowHandler);
    embeddedChannel.runScheduledPendingTasks();
    embeddedChannel.runPendingTasks();
    Queue<Object> messages = embeddedChannel.outboundMessages();
    assertEquals(1, messages.size());
    clientConnection.send(new WireCommands.SetupAppend(1, new UUID(1, 2), "segment", ""));
    embeddedChannel.runPendingTasks();
    clientConnection.send(new Append("segment", new UUID(1, 2), 1, new Event(Unpooled.EMPTY_BUFFER), 2));
    embeddedChannel.disconnect();
    embeddedChannel.runPendingTasks();
    assertTrue(processor.falure.get());
}
 
Example #13
Source File: TXManagerImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that implements the {@link CacheTransactionManager} interface.
 * Only only one instance per {@link com.gemstone.gemfire.cache.Cache}
 */
public TXManagerImpl(CachePerfStats cachePerfStats, LogWriterI18n logWriter,
    GemFireCacheImpl cache) {
  this.cache = cache;
  this.dm = cache.getDistributedSystem().getDistributionManager();
  this.cachePerfStats = cachePerfStats;
  this.logWriter = logWriter;
  this.hostedTXStates = new CustomEntryConcurrentHashMap<TXId, TXStateProxy>(
      128, CustomEntryConcurrentHashMap.DEFAULT_LOAD_FACTOR,
      TXMAP_CONCURRENCY);
  this.suspendedTXs = new ConcurrentHashMap<TXId, TXStateInterface>();
  this.finishedTXStates = new TXFinishedMap(cache.getDistributedSystem(),
      cache.getCancelCriterion());
  this.waitMap = new ConcurrentHashMap<TransactionId, Queue<Thread>>();
  this.expiryTasks = new ConcurrentHashMap<TransactionId, SystemTimerTask>();
}
 
Example #14
Source File: Tree.java    From berkeleyparser with GNU General Public License v2.0 6 votes vote down vote up
private static <L> Constituent<L> getLeastCommonAncestorConstituentHelper(
		Tree<L> tree, int start, int end, int i, int j) {

	if (start == i && end == j)
		return new Constituent<L>(tree.getLabel(), start, end);

	Queue<Tree<L>> queue = new LinkedList<Tree<L>>();
	queue.addAll(tree.getChildren());
	int currStart = start;
	while (!queue.isEmpty()) {
		Tree<L> remove = queue.remove();
		List<L> currYield = remove.getYield();
		final int currEnd = currStart + currYield.size();
		if (currStart <= i && currEnd >= j) {
			final Constituent<L> leastCommonAncestorConstituentHelper = getLeastCommonAncestorConstituentHelper(
					remove, currStart, currEnd, i, j);
			if (leastCommonAncestorConstituentHelper != null)
				return leastCommonAncestorConstituentHelper;
			else
				break;
		}
		currStart += currYield.size();
	}
	return new Constituent<L>(tree.getLabel(), start, end);
}
 
Example #15
Source File: RefreshContentWrapper.java    From CollapsingRefresh with Apache License 2.0 6 votes vote down vote up
private View findScrollableViewInternal(View content, boolean selfable) {
    View scrollableView = null;
    Queue<View> views = new LinkedBlockingQueue<>(Collections.singletonList(content));
    while (!views.isEmpty() && scrollableView == null) {
        View view = views.poll();
        if (view != null) {
            if ((selfable || view != content) && (view instanceof AbsListView
                    || view instanceof ScrollView
                    || view instanceof ScrollingView
                    || view instanceof NestedScrollingChild
                    || view instanceof NestedScrollingParent
                    || view instanceof WebView
                    || view instanceof ViewPager)) {
                scrollableView = view;
            } else if (view instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) view;
                for (int j = 0; j < group.getChildCount(); j++) {
                    views.add(group.getChildAt(j));
                }
            }
        }
    }
    return scrollableView;
}
 
Example #16
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Similar to {@link #fullDuplexCall}, except that it waits for all streaming requests to be
 * received before starting the streaming responses.
 */
@Override
public StreamObserver<Messages.StreamingOutputCallRequest> halfDuplexCall(
    final StreamObserver<Messages.StreamingOutputCallResponse> responseObserver) {
  final ResponseDispatcher dispatcher = new ResponseDispatcher(responseObserver);
  final Queue<Chunk> chunks = new ArrayDeque<>();
  return new StreamObserver<StreamingOutputCallRequest>() {
    @Override
    public void onNext(StreamingOutputCallRequest request) {
      chunks.addAll(toChunkQueue(request));
    }

    @Override
    public void onCompleted() {
      // Dispatch all of the chunks in one shot.
      dispatcher.enqueue(chunks).completeInput();
    }

    @Override
    public void onError(Throwable cause) {
      dispatcher.onError(cause);
    }
  };
}
 
Example #17
Source File: AbstractJavaEsSparkStreamingTest.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testEsRDDWriteWithMappingExclude() throws Exception {
    Map<String, Object> trip1 = new HashMap<>();
    trip1.put("reason", "business");
    trip1.put("airport", "SFO");

    Map<String, Object> trip2 = new HashMap<>();
    trip2.put("participants", 5);
    trip2.put("airport", "OTP");

    List<Map<String, Object>> docs = new ArrayList<>();
    docs.add(trip1);
    docs.add(trip2);

    String target = wrapIndex(resource("spark-test-scala-write-exclude", "data", version));

    Map<String, String> localConf = new HashMap<>(cfg);
    localConf.put(ES_MAPPING_EXCLUDE, "airport");

    JavaRDD<Map<String, Object>> batch = sc.parallelize(docs);
    Queue<JavaRDD<Map<String, Object>>> rddQueue = new LinkedList<>();
    rddQueue.add(batch);
    JavaDStream<Map<String, Object>> dstream = ssc.queueStream(rddQueue);
    JavaEsSparkStreaming.saveToEs(dstream, target, localConf);
    ssc.start();
    TimeUnit.SECONDS.sleep(2);
    ssc.stop(false, true);

    assertTrue(RestUtils.exists(target));
    assertThat(RestUtils.get(target + "/_search?"), containsString("business"));
    assertThat(RestUtils.get(target +  "/_search?"), containsString("participants"));
    assertThat(RestUtils.get(target +  "/_search?"), not(containsString("airport")));
}
 
Example #18
Source File: Steper.java    From utils with Apache License 2.0 5 votes vote down vote up
public void run() {
    while (true) {
        int second = Calendar.getInstance().get(Calendar.MINUTE) * 60 + Calendar.getInstance().get(Calendar.SECOND);
        final Queue<IRingTask> tasks = queue.next(second);
        stepPool.execute(new Runnable() {
            public void run() {
                final Iterator<IRingTask> it = tasks.iterator();
                while (it.hasNext()) {
                    final IRingTask task = it.next();
                    if (task.getCycle() <= 0) {
                        taskPool.execute(new Runnable() {
                            public void run() {
                                if (task.doTask()) {
                                    it.remove();
                                    if (null != listener) {
                                        listener.onSuccess(task);
                                    }
                                } else {
                                    if (null != listener) {
                                        listener.onFailed(task);
                                    }
                                }
                            }
                        });
                    } else {
                        task.countDown();
                    }
                }
            }
        });

        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
            continue;
        }
    }
}
 
Example #19
Source File: TransactionInvokerImplTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testInvoke() {
    final TransactionInvokerImpl invoker = new TransactionInvokerImpl(db, new ArrayList<>());
    final TransactionCommand command = mock(TransactionCommand.class);
    invoker.invoke(command);

    Queue<TransactionCommand> inputQueue = getInternalState(invoker, "inputQueue");
    assertEquals(1, inputQueue.size());
    assertTrue(inputQueue.contains(command));
}
 
Example #20
Source File: ConcurrentLinkedDequeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A deserialized serialized 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 #21
Source File: SingleConsumerQueueTest.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "populated")
public void removeElement_toEmpty(Queue<Integer> queue) {
  while (!queue.isEmpty()) {
    Integer value = queue.peek();
    assertThat(queue.remove(value), is(true));
    assertThat(queue.contains(value), is(false));
  }
  assertThat(queue, is(deeplyEmpty()));
}
 
Example #22
Source File: SelectQuery.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private String extractTargetTableName(Queue<String> tokens) throws SQLException {
    /* Drops FROM keyword */
    tokens.poll();
    if (!Constants.TABLE.equals(tokens.peek())) {
        throw new SQLException("'TABLE' keyword is expected");
    }
    tokens.poll();
    if (!ParserUtil.isStringLiteral(tokens.peek())) {
        throw new SQLException("Syntax Error : String literal is expected");
    }
    return tokens.poll();
}
 
Example #23
Source File: 11995 I Can Guess the Data Structure.java    From UVA with GNU General Public License v3.0 5 votes vote down vote up
public static void main (String [] abc) throws IOException {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	while ((s=br.readLine())!=null) {
		int opCount=Integer.parseInt(s);
		Stack<Integer> stk=new Stack<>(); boolean stkOK=true;
		Queue<Integer> q=new LinkedList<>(); boolean qOK=true;
		PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder()); boolean pqOK=true;
		
		for (int i=0;i<opCount;i++) {
			StringTokenizer st=new StringTokenizer(br.readLine());
			String op=st.nextToken();
			int value=Integer.parseInt(st.nextToken());
			if (op.equals("1")) {
				if (stkOK) stk.push(value);
				if (qOK) q.offer(value);
				if (pqOK) pq.offer(value);
			} else if (op.equals("2")) {
				if (stkOK && (stk.size()==0 || !stk.pop().equals(value))) stkOK=false;
				if (qOK && (q.size()==0 || !q.poll().equals(value))) qOK=false;
				if (pqOK && (pq.size()==0 || !pq.poll().equals(value))) pqOK=false;
			}
		}
		
		if (!stkOK && !qOK && !pqOK) System.out.println("impossible");
		else if ((stkOK && qOK) || (stkOK && pqOK) || (qOK && pqOK)) System.out.println("not sure");
		else if (stkOK) System.out.println("stack");
		else if (qOK) System.out.println("queue");
		else if (pqOK) System.out.println("priority queue");
	}
}
 
Example #24
Source File: SearchingTechniques.java    From big-o with MIT License 5 votes vote down vote up
private static <T> boolean doBfs(
		Map<GraphNode<T>, List<GraphNode<T>>> graph,
		GraphNode<T> startNode, GraphNode<T> nodeToBeSearched) {
	if (startNode.equals(nodeToBeSearched)) {
		return true;
	}

	Set<GraphNode<T>> visited = new HashSet<GraphNode<T>>();
	Queue<GraphNode<T>> queue = new LinkedList<GraphNode<T>>();
	visited.add(startNode);

	while (!queue.isEmpty()) {
		GraphNode<T> node = queue.remove();

		for (GraphNode<T> adjacentNode : graph.get(node)) {
			if (!visited.contains(adjacentNode)) {
				if (adjacentNode.equals(nodeToBeSearched)) {
					return true;
				}
				visited.add(adjacentNode);
				queue.add(adjacentNode);
			}
		}
	}

	return false;
}
 
Example #25
Source File: JavaCompiler.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform dataflow checks on attributed parse trees.
 * These include checks for definite assignment and unreachable statements.
 * If any errors occur, an empty list will be returned.
 * @returns the list of attributed parse trees
 */
public Queue<Env<AttrContext>> flow(Queue<Env<AttrContext>> envs) {
    ListBuffer<Env<AttrContext>> results = new ListBuffer<>();
    for (Env<AttrContext> env: envs) {
        flow(env, results);
    }
    return stopIfError(CompileState.FLOW, results);
}
 
Example #26
Source File: ConfigurationAnnotations.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the full set of modules transitively {@linkplain Module#includes included} from the
 * given seed modules.  If a module is malformed and a type listed in {@link Module#includes}
 * is not annotated with {@link Module}, it is ignored.
 */
static ImmutableSet<TypeElement> getTransitiveModules(
    Types types, Elements elements, Iterable<TypeElement> seedModules) {
  TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType();
  Queue<TypeElement> moduleQueue = Queues.newArrayDeque(seedModules);
  Set<TypeElement> moduleElements = Sets.newLinkedHashSet();
  for (TypeElement moduleElement = moduleQueue.poll();
      moduleElement != null;
      moduleElement = moduleQueue.poll()) {
    Optional<AnnotationMirror> moduleMirror = getAnnotationMirror(moduleElement, Module.class)
        .or(getAnnotationMirror(moduleElement, ProducerModule.class));
    if (moduleMirror.isPresent()) {
      ImmutableSet.Builder<TypeElement> moduleDependenciesBuilder = ImmutableSet.builder();
      moduleDependenciesBuilder.addAll(
          MoreTypes.asTypeElements(getModuleIncludes(moduleMirror.get())));
      // (note: we don't recurse on the parent class because we don't want the parent class as a
      // root that the component depends on, and also because we want the dependencies rooted
      // against this element, not the parent.)
      addIncludesFromSuperclasses(types, moduleElement, moduleDependenciesBuilder, objectType);
      ImmutableSet<TypeElement> moduleDependencies = moduleDependenciesBuilder.build();
      moduleElements.add(moduleElement);
      for (TypeElement dependencyType : moduleDependencies) {
        if (!moduleElements.contains(dependencyType)) {
          moduleQueue.add(dependencyType);
        }
      }
    }
  }
  return ImmutableSet.copyOf(moduleElements);
}
 
Example #27
Source File: ThroughputTest.java    From beepbeep-3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testPassthroughPush() 
{
	long num_events = 1000000;
	Vector<Object> events = new Vector<Object>();
	events.add("A");
	events.add("B");
	events.add("C");
	events.add("D");
	QueueSource cp = new QueueSource(1);
	cp.setEvents(events);
	Passthrough pt = new Passthrough(1);
	Connector.connect(cp, pt);
	for (int i = 0; i < 10; i++)
	{
		Passthrough pt2 = new Passthrough(1);
		Connector.connect(pt, pt2);
		pt = pt2;
	}
	QueueSink s = new QueueSink(1);
	Connector.connect(pt, s);
	Queue<Object> q = s.getQueue(0);
	float start_time = System.nanoTime();
	for (long n = 0; n < num_events; n++)
	{
		cp.push();
		q.poll();
	}
	float end_time = System.nanoTime();
	long throughput = (long) (((float) num_events) / (end_time - start_time) * 1000000000f);
	System.out.println("Throughput on passthrough (push): " + throughput + " ev/s");
	assertTrue(true);
}
 
Example #28
Source File: FluxConcatMap.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
ConcatMapDelayed(CoreSubscriber<? super R> actual,
		Function<? super T, ? extends Publisher<? extends R>> mapper,
		Supplier<? extends Queue<T>> queueSupplier,
		int prefetch, boolean veryEnd) {
	this.actual = actual;
	this.mapper = mapper;
	this.queueSupplier = queueSupplier;
	this.prefetch = prefetch;
	this.limit = Operators.unboundedOrLimit(prefetch);
	this.veryEnd = veryEnd;
	this.inner = new ConcatMapInner<>(this);
}
 
Example #29
Source File: SenderProxy.java    From aeron with Apache License 2.0 5 votes vote down vote up
public SenderProxy(
    final ThreadingMode threadingMode, final Queue<Runnable> commandQueue, final AtomicCounter failCount)
{
    this.threadingMode = threadingMode;
    this.commandQueue = commandQueue;
    this.failCount = failCount;
}
 
Example #30
Source File: PolicyModelTranslator.java    From openjdk-8 with GNU General Public License v2.0 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())));
        }
    }
}