Пример #1
0
  @Override
  public T next() {
    T t;
    boolean hasResult;

    if (!resultsQueue.isEmpty()) {
      t = resultsQueue.poll();
      hasResult = true;
    } else {
      t = null;
      hasResult = false;
    }

    // Always restart when we call next.
    while (!deferQueue.isEmpty()) {
      executorService.submit(deferQueue.poll());
    }

    // If we don't have a result...
    while (!hasResult) {

      // recheck that there is an element to be had and then wait.
      if (!hasNext()) {
        throw new NoSuchElementException();
      }

      try {
        return resultsQueue.take();
      } catch (final InterruptedException e) {
        e.printStackTrace();
      }
    }

    return t;
  }
Пример #2
0
 void checkEmpty(BlockingQueue q) {
   try {
     assertTrue(q.isEmpty());
     assertEquals(0, q.size());
     assertNull(q.peek());
     assertNull(q.poll());
     assertNull(q.poll(0, MILLISECONDS));
     assertEquals("[]", q.toString());
     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
     assertFalse(q.iterator().hasNext());
     try {
       q.element();
       shouldThrow();
     } catch (NoSuchElementException success) {
     }
     try {
       q.iterator().next();
       shouldThrow();
     } catch (NoSuchElementException success) {
     }
     try {
       q.remove();
       shouldThrow();
     } catch (NoSuchElementException success) {
     }
   } catch (InterruptedException ie) {
     threadUnexpectedException(ie);
   }
 }
Пример #3
0
 private void checkProblemFactChanges() {
   BlockingQueue<ProblemFactChange> problemFactChangeQueue =
       basicPlumbingTermination.getProblemFactChangeQueue();
   if (!problemFactChangeQueue.isEmpty()) {
     solverScope.setRestartSolver(true);
     solverScope.setWorkingSolutionFromBestSolution();
     Score score = null;
     int count = 0;
     ProblemFactChange problemFactChange = problemFactChangeQueue.poll();
     while (problemFactChange != null) {
       score = doProblemFactChange(problemFactChange);
       count++;
       problemFactChange = problemFactChangeQueue.poll();
     }
     Solution newBestSolution = solverScope.getScoreDirector().cloneWorkingSolution();
     // TODO BestSolutionRecaller.solverStarted() already calls countUninitializedVariables()
     int newBestUninitializedVariableCount =
         solverScope.getSolutionDescriptor().countUninitializedVariables(newBestSolution);
     bestSolutionRecaller.updateBestSolution(
         solverScope, newBestSolution, newBestUninitializedVariableCount);
     logger.info(
         "Done {} ProblemFactChange(s): new score ({}) possibly uninitialized. Restarting solver.",
         count,
         score);
   }
 }
Пример #4
0
  private void testClient(BayeuxClient client) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    client
        .getChannel(Channel.META_CONNECT)
        .addListener(
            new ClientSessionChannel.MessageListener() {
              public void onMessage(ClientSessionChannel channel, Message message) {
                if (message.isSuccessful()) latch.countDown();
              }
            });

    final BlockingQueue<Message> metaMessages = new ArrayBlockingQueue<>(16);
    client
        .getChannel("/meta/*")
        .addListener(
            new ClientSessionChannel.MessageListener() {
              public void onMessage(ClientSessionChannel channel, Message message) {
                // Skip /meta/connect messages because they arrive without notice
                // and most likely fail the test that it is waiting for other messages
                if (!Channel.META_CONNECT.equals(message.getChannel())) metaMessages.offer(message);
              }
            });

    client.handshake();

    Message message = metaMessages.poll(5, TimeUnit.SECONDS);
    Assert.assertNotNull(message);
    Assert.assertEquals(Channel.META_HANDSHAKE, message.getChannel());
    Assert.assertTrue(message.isSuccessful());
    String id = client.getId();
    Assert.assertNotNull(id);

    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));

    final BlockingQueue<Message> messages = new ArrayBlockingQueue<>(16);
    ClientSessionChannel.MessageListener subscriber =
        new ClientSessionChannel.MessageListener() {
          public void onMessage(ClientSessionChannel channel, Message message) {
            messages.offer(message);
          }
        };
    ClientSessionChannel aChannel = client.getChannel("/a/channel");
    aChannel.subscribe(subscriber);

    message = metaMessages.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(Channel.META_SUBSCRIBE, message.getChannel());
    Assert.assertTrue(message.isSuccessful());

    String data = "data";
    aChannel.publish(data);
    message = messages.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(data, message.getData());

    aChannel.unsubscribe(subscriber);
    message = metaMessages.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(Channel.META_UNSUBSCRIBE, message.getChannel());
    Assert.assertTrue(message.isSuccessful());

    disconnectBayeuxClient(client);
  }
Пример #5
0
  @Test
  public void testPoll3() throws InterruptedException {
    // 插入1条消息
    String myType = TYPE + "_";
    SwallowMessage myTypeMsg = createMessage();
    myTypeMsg.setType(myType);
    messageDAO.saveMessage(TOPIC_NAME, myTypeMsg);

    Set<String> messageTypeSet = new HashSet<String>();
    messageTypeSet.add(myType);
    ConsumerInfo consumerInfo =
        new ConsumerInfo(
            "consumerId", Destination.topic(TOPIC_NAME), ConsumerType.DURABLE_AT_LEAST_ONCE);
    BlockingQueue<SwallowMessage> queue =
        swallowBuffer.createMessageQueue(
            consumerInfo,
            tailMessageId,
            tailMessageId,
            MessageFilter.createInSetMessageFilter(messageTypeSet));

    SwallowMessage m = queue.poll(500, TimeUnit.MILLISECONDS);
    while (m == null) {
      m = queue.poll(50, TimeUnit.MILLISECONDS);
    }
    Assert.assertEquals(myType, m.getType());
  }
  @Override
  public void update(float delta) {
    int processed = 0;
    PerformanceMonitor.startActivity("BlockChangedEventQueue");
    BlockChangedEvent event = eventQueue.poll();
    while (event != null) {
      logger.finer(
          String.format(
              "%s: %s -> %s",
              event.getBlockPosition(),
              event.getOldType().getBlockFamily(),
              event.getNewType().getBlockFamily()));
      getOrCreateEntityAt(event.getBlockPosition()).send(event);
      if (processed++ >= 4) {
        break;
      }
      event = eventQueue.poll();
    }
    PerformanceMonitor.endActivity();
    PerformanceMonitor.startActivity("Temp Blocks Cleanup");
    for (EntityRef entity : tempBlocks) {
      BlockComponent blockComp = entity.getComponent(BlockComponent.class);
      if (blockComp == null || !blockComp.temporary) continue;

      HealthComponent healthComp = entity.getComponent(HealthComponent.class);
      if (healthComp == null || healthComp.currentHealth == healthComp.maxHealth) {
        entity.destroy();
      }
    }
    tempBlocks.clear();
    PerformanceMonitor.endActivity();
  }
Пример #7
0
  @Test
  public void testMessage() throws Exception {
    failed = false;

    speaker1.send("MyUDPTopic", new MyMessage(MESSAGE + "1"));
    MyMessage m = queue.poll(2000l, TimeUnit.MILLISECONDS);
    assertNotNull(m);
    assertEquals(m.getMessage(), MESSAGE + "1");

    if (failed) {
      fail();
    }

    speaker1.send("BadTopic", new MyMessage(MESSAGE + "2"));
    m = queue.poll(500l, TimeUnit.MILLISECONDS);
    assertNull(m);

    queue.clear();

    speaker2.send("MyUDPTopic", new MyMessage(MESSAGE + "1"));
    m = queue.poll(2000l, TimeUnit.MILLISECONDS);
    assertNotNull(m);
    assertEquals(m.getMessage(), MESSAGE + "1");

    if (failed) {
      fail();
    }

    speaker2.send("BadTopic", new MyMessage(MESSAGE + "2"));
    m = queue.poll(500l, TimeUnit.MILLISECONDS);
    assertNull(m);

    queue.clear();
  }
  @Test
  public void testPassingValidSubscriptionSendsOutExpectedNotifications() throws Exception {

    IQ request =
        toIq(
            readStanzaAsString("/iq/pubsub/subscribe/authorizationPendingGrantReply.stanza")
                .replaceFirst("subscription='subscribed'", "subscription='subscribed'"));

    NodeAffiliation subscriptionMockActor = Mockito.mock(NodeAffiliation.class);
    Mockito.when(subscriptionMockActor.getAffiliation()).thenReturn(Affiliations.owner);

    NodeSubscription subscriptionMockSubscriber = Mockito.mock(NodeSubscription.class);
    Mockito.when(subscriptionMockSubscriber.getSubscription()).thenReturn(Subscriptions.subscribed);

    Mockito.when(dataStore.nodeExists(node)).thenReturn(true);
    Mockito.when(dataStore.getUserAffiliation(node, jid)).thenReturn(subscriptionMockActor);

    Mockito.when(dataStore.getUserSubscription(node, new JID(subscriber)))
        .thenReturn(subscriptionMockSubscriber);

    event.setChannelManager(dataStore);

    ArrayList<NodeSubscription> subscribers = new ArrayList<NodeSubscription>();
    subscribers.add(new NodeSubscriptionMock(new JID("*****@*****.**")));
    subscribers.add(new NodeSubscriptionMock(new JID("*****@*****.**")));

    Mockito.doReturn(new ResultSetImpl<NodeSubscription>(subscribers))
        .when(dataStore)
        .getNodeSubscriptionListeners(Mockito.anyString());

    event.setChannelManager(dataStore);
    event.process(element, jid, request, null);

    Assert.assertEquals(2, queue.size());
    Packet notification = queue.poll(100, TimeUnit.MILLISECONDS);
    Assert.assertEquals("*****@*****.**", notification.getTo().toString());
    notification = queue.poll(100, TimeUnit.MILLISECONDS);
    Assert.assertEquals("*****@*****.**", notification.getTo().toString());

    Assert.assertEquals(
        node,
        notification.getElement().element("event").element("subscription").attributeValue("node"));
    Assert.assertTrue(notification.toXML().contains(JabberPubsub.NS_PUBSUB_EVENT));
    Assert.assertEquals(
        "subscribed",
        notification
            .getElement()
            .element("event")
            .element("subscription")
            .attributeValue("subscription"));
    Assert.assertEquals(
        subscriber,
        notification.getElement().element("event").element("subscription").attributeValue("jid"));
  }
Пример #9
0
  public ByteBuffer take() throws InterruptedException {
    final boolean logFiner = logger.isLoggable(Level.FINER);
    final boolean logFinest = logFiner || logger.isLoggable(Level.FINEST);
    ByteBuffer retBuff = thePool.poll();
    try {
      if (retBuff != null) {
        return retBuff;
      }

      retBuff = tryAllocateBuffer();

      if (retBuff == null) {
        for (int i = 0; i < maxPollIter; i++) {
          retBuff = thePool.poll();
          if (retBuff != null) {
            break;
          }
        }
      }

      if (retBuff != null) {
        return retBuff;
      }

      retBuff = thePool.take();

      return retBuff;
    } finally {
      if (logFiner) {
        StringBuilder sb = new StringBuilder();
        sb.append("<ByteBufferPool> TAKE FROM POOL in poll(): buffer: ")
            .append(Utils.buffToString(retBuff));
        sb.append("; qSize: ").append(thePool.size()).append(" allocSize: ").append(poolSize.get());
        if (logFinest) {
          sb.append(" Trace: ");
          logger.log(Level.INFO, sb.toString(), new Throwable());
        } else {
          logger.log(Level.INFO, sb.toString());
        }
      }
      if (trackAllocations && retBuff != null) {
        if (!checkBuffer(retBuff, false, true)) {
          logger.log(
              Level.WARNING,
              " \n\n  <ByteBufferPool> trackAllocations ASSERTION FAILURE. retBuf = "
                  + Utils.buffToString(retBuff)
                  + "; TAKE FROM POOL! expect: false update: true",
              new Exception("ASSERTION_FAILURE"));
        }
      }
    }
  }
  @Test
  public void requireConnectionThroughGetState() throws Exception {
    SocketAddress addr = mock(SocketAddress.class);
    createTransportSet(addr);

    assertEquals(ConnectivityState.IDLE, transportSet.getState(false));
    assertEquals(ConnectivityState.CONNECTING, transportSet.getState(true));
    assertEquals(ConnectivityState.CONNECTING, transportSet.getState(true));

    transportSet
        .obtainActiveTransport()
        .newStream(method, new Metadata(), waitForReadyCallOptions, statsTraceCtx);
    assertEquals(ConnectivityState.CONNECTING, transportSet.getState(true));

    // Fail it
    transports.peek().listener.transportShutdown(Status.UNAVAILABLE);
    // requireConnection == true doesn't skip the back-off
    assertEquals(ConnectivityState.TRANSIENT_FAILURE, transportSet.getState(true));
    transports.poll().listener.transportTerminated();
    fakeClock.forwardMillis(9);
    assertEquals(ConnectivityState.TRANSIENT_FAILURE, transportSet.getState(true));
    fakeClock.forwardMillis(1);
    // Only when back-off is over, do we try to connect again
    assertEquals(ConnectivityState.CONNECTING, transportSet.getState(false));

    // Let it through and fail, thus a go-away
    transports.peek().listener.transportReady();
    transports.peek().listener.transportShutdown(Status.UNAVAILABLE);
    assertEquals(ConnectivityState.IDLE, transportSet.getState(false));
    transports.poll().listener.transportTerminated();

    // Request for connecting again
    assertEquals(ConnectivityState.CONNECTING, transportSet.getState(true));
    // And fail it again
    transports.peek().listener.transportShutdown(Status.UNAVAILABLE);
    assertEquals(ConnectivityState.TRANSIENT_FAILURE, transportSet.getState(true));

    // Shut it down
    transportSet.shutdown();
    assertEquals(ConnectivityState.SHUTDOWN, transportSet.getState(true));
    assertEquals(ConnectivityState.SHUTDOWN, transportSet.getState(false));
    assertFalse(transportSet.isTerminated());

    // Terminate it
    transports.poll().listener.transportTerminated();
    assertTrue(transportSet.isTerminated());
    assertEquals(ConnectivityState.SHUTDOWN, transportSet.getState(true));
    assertEquals(ConnectivityState.SHUTDOWN, transportSet.getState(false));

    fakeExecutor.runDueTasks(); // What tasks are scheduled is not important to this test.
  }
  public void testLooperDestruction() {

    final BlockingQueue<JSONObject> messages = new LinkedBlockingQueue<JSONObject>();

    // If something terrible happens in the worker thread, we
    // should make sure
    final MPDbAdapter explodingDb =
        new MPDbAdapter(getContext()) {
          @Override
          public int addJSON(JSONObject message, MPDbAdapter.Table table) {
            messages.add(message);
            throw new RuntimeException("BANG!");
          }
        };
    final AnalyticsMessages explodingMessages =
        new AnalyticsMessages(getContext()) {
          // This will throw inside of our worker thread.
          @Override
          public MPDbAdapter makeDbAdapter(Context context) {
            return explodingDb;
          }
        };
    MixpanelAPI mixpanel =
        new TestUtils.CleanMixpanelAPI(
            getContext(), mMockPreferences, "TEST TOKEN testLooperDisaster") {
          @Override
          protected AnalyticsMessages getAnalyticsMessages() {
            return explodingMessages;
          }
        };

    try {
      mixpanel.clearPreferences();
      assertFalse(explodingMessages.isDead());

      mixpanel.track("event1", null);
      JSONObject found = messages.poll(1, TimeUnit.SECONDS);
      assertNotNull(found);
      Thread.sleep(1000);
      assertTrue(explodingMessages.isDead());

      mixpanel.track("event2", null);
      JSONObject shouldntFind = messages.poll(1, TimeUnit.SECONDS);
      assertNull(shouldntFind);
      assertTrue(explodingMessages.isDead());
    } catch (InterruptedException e) {
      fail("Unexpected interruption");
    }
  }
Пример #12
0
  public Message receive(long timeout) throws JMSException {
    if (messageListener != null) {
      throw new JMSException(Messages.getString("MessageConsumerImpl.0")); // $NON-NLS-1$
    }

    if (timeout == DO_NOT_WAIT) {
      return messages.poll();
    }

    try {
      return messages.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
      throw new JMSException(ex.getMessage());
    }
  }
  @Test
  public void testPipelined() throws Exception {
    server.setHandler(new AsyncStreamHandler());
    server.start();

    try (final Socket socket = new Socket("localhost", connector.getLocalPort())) {
      socket.setSoTimeout(1000);

      byte[] content = new byte[32 * 4096];
      Arrays.fill(content, (byte) 120);

      OutputStream out = socket.getOutputStream();
      String header =
          "POST / HTTP/1.1\r\n"
              + "Host: localhost\r\n"
              + "Content-Length: "
              + content.length
              + "\r\n"
              + "Content-Type: bytes\r\n"
              + "\r\n";
      byte[] h = header.getBytes(StandardCharsets.ISO_8859_1);
      out.write(h);
      out.write(content);

      header =
          "POST / HTTP/1.1\r\n"
              + "Host: localhost\r\n"
              + "Content-Length: "
              + content.length
              + "\r\n"
              + "Content-Type: bytes\r\n"
              + "Connection: close\r\n"
              + "\r\n";
      h = header.getBytes(StandardCharsets.ISO_8859_1);
      out.write(h);
      out.write(content);
      out.flush();

      InputStream in = socket.getInputStream();
      String response = IO.toString(in);
      assertTrue(response.indexOf("200 OK") > 0);

      long total = __total.poll(5, TimeUnit.SECONDS);
      assertEquals(content.length, total);
      total = __total.poll(5, TimeUnit.SECONDS);
      assertEquals(content.length, total);
    }
  }
Пример #14
0
  public void run() {
    generateDefaultMessageImage();
    while (!stopped) {
      try {
        if (queue.size() == 0) {
          display(DEFAULT_FILE_NAME);
          LOG.info("Waiting for updates");
          updates.take();
          continue;
        }

        TwitterBoardNotification notification = queue.take();
        while (queue.size() >= MAX_MESSAGES_IN_QUEUE) {
          LOG.info("Queue size is to big ({}). Skipping message {} ", queue.size(), notification);
          notification = queue.take();
        }

        long drawFinishTime = 0l;
        boolean redraw = true;
        boolean completed = false;
        while (!completed) {
          if (redraw) {
            LOG.info("Going to display {}", notification);
            int width = generateMessageImage(notification);
            LOG.info(
                "Width of this message {} and repeat count is {}",
                width,
                configuration.getRepeatCount());
            display(CUSTOM_FILE_NAME);
            drawFinishTime =
                System.currentTimeMillis()
                    + width
                        * configuration.getScrollSpeed()
                        * (Math.max(MIN_REPEAT_COUNT, configuration.getRepeatCount()));
            redraw = false;
          }
          long timeout = drawFinishTime - System.currentTimeMillis();
          if (timeout < 0) {
            completed = true;
            continue;
          }
          LOG.info("Will sleep for {} ms", timeout);
          TwitterBoardUpdate update = updates.poll(timeout, TimeUnit.MILLISECONDS);
          if (update != null) {
            LOG.info("Update detected: {}", update);
            if (update.isNewNotification()) {
              completed = configuration.getQueueSize() == 0;
            } else if (update.isNewConfiguration()) {
              LOG.info("Restarting message due to configuration update");
              redraw = update.isRedraw();
            }
          } else {
            completed = true;
          }
        }
      } catch (Exception e) {
        LOG.error("Failed to display message: {}", e.getMessage(), e);
      }
    }
  }
  @Test
  public void testBasicHandling() throws IOException, InterruptedException {
    final List<String> messages = new ArrayList<>();
    messages.add("1 syslog 20 this is message 1234\n");
    messages.add("2 syslog 22 this is message 456789\n");
    messages.add("3 syslog 21 this is message ABCDE\n");

    run(messages);
    Assert.assertEquals(messages.size(), events.size());

    boolean found1 = false;
    boolean found2 = false;
    boolean found3 = false;

    TestEvent event;
    while ((event = events.poll()) != null) {
      Map<String, String> metadata = event.metadata;
      Assert.assertTrue(metadata.containsKey(RELPMetadata.TXNR_KEY));

      final String txnr = metadata.get(RELPMetadata.TXNR_KEY);
      if (txnr.equals("1")) {
        found1 = true;
      } else if (txnr.equals("2")) {
        found2 = true;
      } else if (txnr.equals("3")) {
        found3 = true;
      }
    }

    Assert.assertTrue(found1);
    Assert.assertTrue(found2);
    Assert.assertTrue(found3);
  }
Пример #16
0
 private Message waitForMessage(long timeout) throws GtpError {
   Message message = null;
   if (timeout < 0) {
     try {
       message = m_queue.take();
     } catch (InterruptedException e) {
       printInterrupted();
       destroyProcess();
       throwProgramDied();
     }
   } else {
     message = null;
     while (message == null) {
       try {
         message = m_queue.poll(timeout, TimeUnit.MILLISECONDS);
       } catch (InterruptedException e) {
         printInterrupted();
       }
       if (message == null) {
         assert m_timeoutCallback != null;
         if (!m_timeoutCallback.askContinue()) {
           destroyProcess();
           throwProgramDied();
         }
       }
     }
   }
   return message;
 }
Пример #17
0
 public Object poll(int time) {
   try {
     return queue.poll(time, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
     return null;
   }
 }
Пример #18
0
 /**
  * Drains the queue as {@link java.util.concurrent.BlockingQueue#drainTo(java.util.Collection,
  * int)}, but if the requested {@code numElements} elements are not available, it will wait for
  * them up to the specified timeout.
  *
  * @param q the blocking queue to be drained
  * @param buffer where to add the transferred elements
  * @param numElements the number of elements to be waited for
  * @param timeout how long to wait before giving up, in units of {@code unit}
  * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
  * @return the number of elements transferred
  * @throws InterruptedException if interrupted while waiting
  */
 @Beta
 public static <E> int drain(
     BlockingQueue<E> q,
     Collection<? super E> buffer,
     int numElements,
     long timeout,
     TimeUnit unit)
     throws InterruptedException {
   Preconditions.checkNotNull(buffer);
   /*
    * This code performs one System.nanoTime() more than necessary, and in return, the time to
    * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
    * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
    */
   long deadline = System.nanoTime() + unit.toNanos(timeout);
   int added = 0;
   while (added < numElements) {
     // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
     // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
     added += q.drainTo(buffer, numElements - added);
     if (added < numElements) { // not enough elements immediately available; will have to poll
       E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
       if (e == null) {
         break; // we already waited enough, and there are no more elements in sight
       }
       buffer.add(e);
       added++;
     }
   }
   return added;
 }
Пример #19
0
 private XMLOutputFactory getXMLOutputFactory() {
   XMLOutputFactory f = OUTPUT_FACTORY_POOL.poll();
   if (f == null) {
     f = XMLOutputFactory.newInstance();
   }
   return f;
 }
Пример #20
0
 @Test
 public void runTestWithAsyncCompletion() throws Exception {
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   AtomicInteger count = new AtomicInteger();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 count.compareAndSet(0, 1);
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Async async = queue.poll(2, TimeUnit.SECONDS);
   assertEquals(1, count.get());
   assertFalse(reporter.completed());
   completeAsync.accept(async);
   reporter.await();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertTrue(result.succeeded());
   assertFalse(result.failed());
   assertNull(result.failure());
 }
Пример #21
0
 @Test
 public void runTestWithFailBeforeAsync() throws Exception {
   AtomicReference<AssertionError> failure = new AtomicReference<>();
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 try {
                   context.fail();
                 } catch (AssertionError e) {
                   failure.set(e);
                 }
                 queue.add(context.async());
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   reporter.await();
   Async async = queue.poll(2, TimeUnit.SECONDS);
   async.complete();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertFalse(result.succeeded());
   assertTrue(result.failed());
   assertNotNull(result.failure());
   assertSame(failure.get(), result.failure().cause());
 }
Пример #22
0
 /**
  * Returns the next job or releases a job slot. If a non-null value is returned, the caller must
  * submit the job to execution. Should only be caller by a caller than currently holds a job slot.
  *
  * @return
  */
 private synchronized PrioritizedRequest nextOrRelease() {
   PrioritizedRequest request = _queue.poll();
   if (request == null) {
     _semaphore.release();
   }
   return request;
 }
Пример #23
0
 public ViewState takeTask(final long timeout, final TimeUnit unit, final boolean useLastState) {
   ViewState task = null;
   try {
     task = queue.poll(timeout, unit);
     if (task != null && useLastState) {
       final ArrayList<ViewState> list = new ArrayList<ViewState>();
       // Workaround for possible ConcurrentModificationException
       while (true) {
         list.clear();
         try {
           if (queue.drainTo(list) > 0) {
             task = list.get(list.size() - 1);
           }
           break;
         } catch (Throwable ex) {
           // Go to next attempt
           LCTX.e(
               "Unexpected error on retrieving last view state from draw queue: "
                   + ex.getMessage());
         }
       }
     }
   } catch (final InterruptedException e) {
     Thread.interrupted();
   } catch (Throwable ex) {
     // Go to next attempt
     LCTX.e("Unexpected error on retrieving view state from draw queue: " + ex.getMessage());
   }
   return task;
 }
Пример #24
0
  /**
   * Send the Java thread that represents this fiber to sleep until it recieves a resume or exit
   * message. On entry, assumes that the GIL is not held. On exit, holding the GIL.
   */
  public Object waitForResume() {
    RubyNode.notDesignedForCompilation();

    FiberMessage message = null;

    do {
      try {
        // TODO(cs) what is a suitable timeout?
        message = messageQueue.poll(1, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        // Poll again
      }
    } while (message == null);

    if (message instanceof FiberExitMessage) {
      throw new FiberExitException();
    }

    final FiberResumeMessage resumeMessage = (FiberResumeMessage) message;

    threadManager.enterGlobalLock(resumeMessage.getThread());

    fiberManager.setCurrentFiber(this);

    lastResumedByFiber = resumeMessage.getSendingFiber();
    return resumeMessage.getArg();
  }
  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
      value = "RV_RETURN_VALUE_IGNORED",
      justification =
          "We don't care about return value from queue.poll(), queue is used as a barrier")
  public boolean await(long timeout, TimeUnit unit) {
    if (applicationFactory.getApplication() == null) {
      // We are probably in setup. Anyways, with no application Crowd Embedded will not work so we
      // assume
      // there is no synchronization currently occuring.
      return true;
    }

    long current = System.currentTimeMillis();
    final long deadLine = System.currentTimeMillis() + unit.toMillis(timeout);
    publisher.register(this);
    try {
      boolean synchroniseRunning = isSynchroniseRunning();
      while (synchroniseRunning && current < deadLine) {
        queue.poll(Math.min(pollingPeriod, deadLine - current), TimeUnit.MILLISECONDS);

        synchroniseRunning = isSynchroniseRunning();
        current = System.currentTimeMillis();
      }
      return !synchroniseRunning;
    } catch (InterruptedException e) {
      return !isSynchroniseRunning();
    } finally {
      publisher.unregister(this);
    }
  }
Пример #26
0
 @Test
 public void testAssertAsyncFailureHandlerSucceededAsync() throws Exception {
   BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
   BlockingQueue<Async> resultQueue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 handlerQueue.add(
                     context.<String>asyncAssertFailure(
                         r -> {
                           resultQueue.add(context.async());
                         }));
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
   handler.handle(Future.failedFuture(new Throwable()));
   Async result = resultQueue.poll(2, TimeUnit.SECONDS);
   assertFalse(reporter.completed());
   result.complete();
   reporter.await();
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   assertEquals("my_test", reporter.results.get(0).name());
   assertFalse(reporter.results.get(0).failed());
 }
  @Test
  public void receiveMessagesAckCheck() throws Exception {
    BlockingQueue<MmsMessage> q = new LinkedBlockingQueue<>();

    Session s = connectNormally(msg -> q.add(msg));

    t.send(new Broadcast().setSenderId("abc"), 1, 0);

    MmsMessage mm = q.poll(2, TimeUnit.SECONDS);
    assertEquals(1, mm.getMessageId());
    assertEquals(0, mm.getLatestReceivedId());
    assertEquals("abc", mm.cast(Broadcast.class).getSenderId());

    // We need to acquire this lock to make sure we are out of the receiving loop (last ack adjusted
    s.receiveLock.lock();
    s.receiveLock.unlock();

    CompletableFuture<Void> cf = new CompletableFuture<>();
    s.sendMessage(new Broadcast().setSenderId("cba"), cf);

    mm = t.t();
    assertEquals(1, mm.getMessageId());
    assertEquals(1, mm.getLatestReceivedId());
    assertEquals("cba", mm.cast(Broadcast.class).getSenderId());

    s.closeSession(MmsConnectionClosingCode.NORMAL);
  }
Пример #28
0
  /**
   * Take a byte buffer from the pool. The caller is responsible of calling release() once for the
   * returned buffer to return it to the pool.
   */
  public ByteBuffer take() {
    ByteBuffer buffer = availPool.poll();
    if (buffer != null) return buffer;

    if (numBuffers.incrementAndGet() <= maxBuffers) {
      log.debug("increasing buffer pool size to {}", numBuffers.get());
      ByteBuffer buf = BytesUtil.instance.allocateDirect(bufSize);
      bufferPool.put(buf, PRESENT);
      return buf;
    } else {
      numBuffers.decrementAndGet();
      /* Temporary buffers are non-direct because the NIO library has its
       * own cache for them, managing this case more cleverly than we
       * we can from here. The library will get the buffer from its cache
       * when a write is requested, so it will be able to release it
       * immediately, whereas we would leave the task up to the garbage
       * collector.
       *
       * The price we pay for allocating a non-direct buffer is one extra
       * copy at write-time.
       */
      log.info("pool is empty, allocating a temporary buffer");
      return BytesUtil.instance.allocate(bufSize);
    }
  }
Пример #29
0
 @Test
 public void runTestWithFailAfterAsync() throws Exception {
   RuntimeException failure = new RuntimeException();
   BlockingQueue<Async> queue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 queue.add(context.async());
                 throw failure;
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   reporter.await();
   Async async = queue.poll(2, TimeUnit.SECONDS);
   async.complete();
   assertTrue(reporter.completed());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   TestResult result = reporter.results.get(0);
   assertEquals("my_test", result.name());
   assertFalse(result.succeeded());
   assertTrue(result.failed());
   assertNotNull(result.failure());
   assertSame(failure, result.failure().cause());
 }
Пример #30
0
 private XMLInputFactory getXMLInputFactory() {
   XMLInputFactory f = INPUT_FACTORY_POOL.poll();
   if (f == null) {
     f = createXMLInputFactory(true);
   }
   return f;
 }