Java Code Examples for java.util.concurrent.CountDownLatch

The following are top voted examples for showing how to use java.util.concurrent.CountDownLatch. 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: vertx-jooq-async   File: VertxSomethingCompositeDaoTest.java   Source Code and License 6 votes vote down vote up
@Test
public void asyncCRUDShouldSucceed() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Somethingcomposite something = createSomething(0, 0);
    SomethingcompositeRecord somethingcompositeRecord = new SomethingcompositeRecord();
    somethingcompositeRecord.from(something);
    compositeDao.insertExecAsync(something).
            thenCompose(
                v-> compositeDao.findByIdAsync(somethingcompositeRecord.key())).
            thenCompose(fetchSomething -> {
                fetchSomething.getSomejsonobject().put("foo", "bar");
                return compositeDao.updateExecAsync(fetchSomething);
            }).
            thenCompose(v2->compositeDao.deleteExecAsync(somethingcompositeRecord.key())).
            whenComplete(failOrCountDown(latch));
    await(latch);
}
 
Example 2
Project: openjdk-jdk10   File: ThreadPoolExecutorTest.java   Source Code and License 6 votes vote down vote up
/**
 * isTerminated is false before termination, true after
 */
public void testIsTerminated() throws InterruptedException {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(1);
        assertFalse(p.isTerminating());
        p.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                assertFalse(p.isTerminating());
                threadStarted.countDown();
                await(done);
            }});
        await(threadStarted);
        assertFalse(p.isTerminating());
        done.countDown();
        try { p.shutdown(); } catch (SecurityException ok) { return; }
        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(p.isTerminated());
        assertFalse(p.isTerminating());
    }
}
 
Example 3
Project: elasticsearch_my   File: AbstractSimpleTransportTestCase.java   Source Code and License 6 votes vote down vote up
public void testNotifyOnShutdown() throws Exception {
    final CountDownLatch latch2 = new CountDownLatch(1);

    serviceA.registerRequestHandler("foobar", StringMessageRequest::new, ThreadPool.Names.GENERIC,
        new TransportRequestHandler<StringMessageRequest>() {
            @Override
            public void messageReceived(StringMessageRequest request, TransportChannel channel) {
                try {
                    latch2.await();
                    logger.info("Stop ServiceB now");
                    serviceB.stop();
                } catch (Exception e) {
                    fail(e.getMessage());
                }
            }
        });
    TransportFuture<TransportResponse.Empty> foobar = serviceB.submitRequest(nodeA, "foobar",
        new StringMessageRequest(""), TransportRequestOptions.EMPTY, EmptyTransportResponseHandler.INSTANCE_SAME);
    latch2.countDown();
    try {
        foobar.txGet();
        fail("TransportException expected");
    } catch (TransportException ex) {

    }
}
 
Example 4
Project: https-github.com-apache-zookeeper   File: LeaderElectionSupportTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNodes3() throws IOException, InterruptedException,
    KeeperException {

  int testIterations = 3;
  final CountDownLatch latch = new CountDownLatch(testIterations);
  final AtomicInteger failureCounter = new AtomicInteger();

  for (int i = 0; i < testIterations; i++) {
    runElectionSupportThread(latch, failureCounter);
  }

  Assert.assertEquals(0, failureCounter.get());

  if (!latch.await(10, TimeUnit.SECONDS)) {
    logger
        .info(
            "Waited for all threads to start, but timed out. We had {} failures.",
            failureCounter);
  }
}
 
Example 5
Project: openjdk-jdk10   File: PhaserTest.java   Source Code and License 6 votes vote down vote up
/**
 * awaitAdvance continues waiting if interrupted before waiting
 */
public void testAwaitAdvanceAfterInterrupt() {
    final Phaser phaser = new Phaser();
    assertEquals(0, phaser.register());
    final CountDownLatch pleaseArrive = new CountDownLatch(1);

    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            Thread.currentThread().interrupt();
            assertEquals(0, phaser.register());
            assertEquals(0, phaser.arrive());
            pleaseArrive.countDown();
            assertTrue(Thread.currentThread().isInterrupted());
            assertEquals(1, phaser.awaitAdvance(0));
            assertTrue(Thread.interrupted());
        }});

    await(pleaseArrive);
    assertThreadBlocks(t, Thread.State.WAITING);
    assertEquals(0, phaser.arrive());
    awaitTermination(t);

    Thread.currentThread().interrupt();
    assertEquals(1, phaser.awaitAdvance(0));
    assertTrue(Thread.interrupted());
}
 
Example 6
Project: spring-react-one   File: ReactivePersonRepositoryIntegrationTest.java   Source Code and License 6 votes vote down vote up
/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 */
@Test
public void shouldInsertAndCountData() throws Exception {

	CountDownLatch countDownLatch = new CountDownLatch(1);

	repository.count() //
			.doOnNext(System.out::println) //
			.thenMany(repository.save(Flux.just(new Person("Hank", "Schrader", 43), //
					new Person("Mike", "Ehrmantraut", 62)))) //
			.last() //
			.flatMap(v -> repository.count()) //
			.doOnNext(System.out::println) //
			.doOnComplete(countDownLatch::countDown) //
			.doOnError(throwable -> countDownLatch.countDown()) //
			.subscribe();

	countDownLatch.await();
}
 
Example 7
Project: buffer-slayer   File: SizeBoundedQueueTest.java   Source Code and License 6 votes vote down vote up
@Test
public void dropHeadWhenFull_dropHeadStrategy() throws InterruptedException {
  SizeBoundedQueue queue = new SizeBoundedQueue(16, OverflowStrategy.dropHead);
  CountDownLatch countDown = new CountDownLatch(1);

  for (int i = 0; i < queue.maxSize; i++) {
    Message next = newMessage(i);
    Deferred<Object, MessageDroppedException, Integer> deferred = new DeferredObject<>();
    queue.offer(next, deferred);
    if (i == 0) {
      deferred.fail(ex -> {
        assertEquals(0, ((TestMessage)ex.dropped.get(0)).key);
        countDown.countDown();
      });
    }
  }
  Message overflow = newMessage(queue.maxSize);
  queue.offer(overflow, new DeferredObject<>());
  countDown.await();

  Object[] ids = collectKeys(queue);
  assertArrayEquals(new Object[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, ids);
}
 
Example 8
Project: openjdk-jdk10   File: TimedAcquireLeak.java   Source Code and License 6 votes vote down vote up
/** No guarantees, but effective in practice. */
private static void forceFullGc() {
    CountDownLatch finalizeDone = new CountDownLatch(1);
    WeakReference<?> ref = new WeakReference<Object>(new Object() {
        protected void finalize() { finalizeDone.countDown(); }});
    try {
        for (int i = 0; i < 10; i++) {
            System.gc();
            if (finalizeDone.await(1L, SECONDS) && ref.get() == null) {
                System.runFinalization(); // try to pick up stragglers
                return;
            }
        }
    } catch (InterruptedException unexpected) {
        throw new AssertionError("unexpected InterruptedException");
    }
    throw new AssertionError("failed to do a \"full\" gc");
}
 
Example 9
Project: buffer-slayer   File: BatchJdbcTemplateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void chainedDeferred() throws InterruptedException {
  reporter = AsyncReporter.builder(new JdbcTemplateSender(underlying))
      .messageTimeout(10, TimeUnit.MILLISECONDS)
      .build();
  batchJdbcTemplate = new BatchJdbcTemplate(underlying, reporter);

  CountDownLatch countDown = new CountDownLatch(1);
  batchJdbcTemplate.update(INSERTION, new Object[]{randomString(), new Date()}).done(d -> {
    assertEquals(new Integer(1), d);
    String expected = randomString();
    batchJdbcTemplate.update(MODIFICATION, new Object[]{expected}).done(dd -> {
      assertEquals(new Integer(1), dd);
      int rowCount = batchJdbcTemplate.queryForObject(ROW_COUNT, Integer.class);
      assertEquals(1, rowCount);
      Object data = batchJdbcTemplate
          .queryForObject("SELECT data FROM test LIMIT 1", String.class);
      assertEquals(expected, data);
      countDown.countDown();
    });
  });
  countDown.await();
}
 
Example 10
Project: flow-platform   File: JobServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_create_job_with_unique_job_number() throws Throwable {
    // given:
    final Node flow = createRootFlow("flow-job-number", "yml/demo_flow2.yaml");
    final int numOfJob = 10;
    final CountDownLatch countDown = new CountDownLatch(numOfJob);

    // when:
    for (int i = 0; i < numOfJob; i++) {
        taskExecutor.execute(() -> {
            jobService.createFromFlowYml(flow.getPath(), JobCategory.MANUAL, null, mockUser);
            countDown.countDown();
        });
    }

    // then:
    countDown.await(30, TimeUnit.SECONDS);
    Assert.assertEquals(numOfJob, jobDao.numOfJob(flow.getPath()).intValue());
}
 
Example 11
Project: elasticsearch_my   File: ScheduleWithFixedDelayTests.java   Source Code and License 6 votes vote down vote up
public void testRunnableRunsAtMostOnceAfterCancellation() throws Exception {
    final int iterations = scaledRandomIntBetween(1, 12);
    final AtomicInteger counter = new AtomicInteger();
    final CountDownLatch doneLatch = new CountDownLatch(iterations);
    final Runnable countingRunnable = () -> {
        counter.incrementAndGet();
        doneLatch.countDown();
    };

    final Cancellable cancellable = threadPool.scheduleWithFixedDelay(countingRunnable, TimeValue.timeValueMillis(10L), Names.GENERIC);
    doneLatch.await();
    cancellable.cancel();
    final int counterValue = counter.get();
    assertThat(counterValue, isOneOf(iterations, iterations + 1));

    if (rarely()) {
        awaitBusy(() -> {
            final int value = counter.get();
            return value == iterations || value == iterations + 1;
        }, 50L, TimeUnit.MILLISECONDS);
    }
}
 
Example 12
Project: dragoman   File: AbstractHttpTestCase.java   Source Code and License 6 votes vote down vote up
@BeforeAll
public static void start() {
  port = getFreePort();

  httpDataProvider = mock(HttpDataProvider.class);
  logger.info("Starting embedded HTTP server on port: {}", port);
  vertx = Vertx.vertx();
  DeploymentOptions options =
      new DeploymentOptions().setConfig(new JsonObject().put("http.port", port)).setInstances(1);

  CountDownLatch latch = new CountDownLatch(1);
  vertx.deployVerticle(
      new HttpServerSimulatorVerticle(httpDataProvider),
      options,
      result -> {
        logger.info("Started embedded HTTP server with result: {}", result);
        latch.countDown();
      });

  try {
    latch.await();
  } catch (InterruptedException e) {
    logger.warn("Failed to wait for the embedded HTTP server to start!");
  }
}
 
Example 13
Project: GitHub   File: EventBusRegistrationRacingTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRacingRegistrations() throws InterruptedException {
    for (int i = 0; i < ITERATIONS; i++) {
        startLatch = new CountDownLatch(THREAD_COUNT);
        registeredLatch = new CountDownLatch(THREAD_COUNT);
        canUnregisterLatch = new CountDownLatch(1);
        unregisteredLatch = new CountDownLatch(THREAD_COUNT);
        
        List<SubscriberThread> threads = startThreads();
        registeredLatch.await();
        eventBus.post("42");
        canUnregisterLatch.countDown();
        for (int t = 0; t < THREAD_COUNT; t++) {
            int eventCount = threads.get(t).eventCount;
            if (eventCount != 1) {
                fail("Failed in iteration " + i + ": thread #" + t + " has event count of " + eventCount);
            }
        }
        // Wait for threads to be done
        unregisteredLatch.await();
    }
}
 
Example 14
Project: hadoop   File: DebugJobFactory.java   Source Code and License 6 votes vote down vote up
public static JobFactory<?> getFactory(
  JobSubmitter submitter, Path scratch, int numJobs, Configuration conf,
  CountDownLatch startFlag, UserResolver resolver) throws IOException {
  GridmixJobSubmissionPolicy policy = GridmixJobSubmissionPolicy.getPolicy(
    conf, GridmixJobSubmissionPolicy.STRESS);
  if (policy == GridmixJobSubmissionPolicy.REPLAY) {
    return new DebugReplayJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);
  } else if (policy == GridmixJobSubmissionPolicy.STRESS) {
    return new DebugStressJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);
  } else if (policy == GridmixJobSubmissionPolicy.SERIAL) {
    return new DebugSerialJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);

  }
  return null;
}
 
Example 15
Project: Mastering-Java-EE-Development-with-WildFly   File: ReadCommittedTestCase.java   Source Code and License 6 votes vote down vote up
@Test
public void testPhantomRead() throws Exception {
	logger.info("start phantom read");
	queryReadAccount.setFirstWaitTime(0);
	queryReadAccount.setSecondWaitTime(2000);
	queryWriteAccount.setAccountNumber(953);
	queryWriteAccount.setAmount(456.77);
	queryWriteAccount.setWaitTime(1000);
	latch = new CountDownLatch(1);
	defaultExecutor.submit(queryWriteAccount);
	defaultExecutor.submit(queryReadAccount);
	latch.await(3000, MILLISECONDS);
	assertEquals("the transaction B add a new account", 456.77, queryWriteAccount.getResult(), 0.0);
	assertEquals("the first query in the transaction A before the transaction ends", 8,
			queryReadAccount.getFirstResult());
	assertEquals("the second query in the transaction A after the transaction ends", 9,
			queryReadAccount.getSecondResult());
}
 
Example 16
Project: openjdk-jdk10   File: ScheduledExecutorSubclassTest.java   Source Code and License 6 votes vote down vote up
/**
 * isTerminated is false before termination, true after
 */
public void testIsTerminated() throws InterruptedException {
    final CountDownLatch done = new CountDownLatch(1);
    final ThreadPoolExecutor p = new CustomExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        p.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                assertFalse(p.isTerminated());
                threadStarted.countDown();
                await(done);
            }});
        await(threadStarted);
        assertFalse(p.isTerminated());
        assertFalse(p.isTerminating());
        done.countDown();
        try { p.shutdown(); } catch (SecurityException ok) { return; }
        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(p.isTerminated());
    }
}
 
Example 17
Project: Pogamut3   File: WaitForFlagChange.java   Source Code and License 6 votes vote down vote up
/**
 * Note that you may call only await() from one thread! If the instance is already in used
 * it may produce unwanted behavior (e.g. dead-lock).
 * 
 * @return value from the flag that raised the latch
 * @throws InterruptedException
 */
public TYPE await() throws PogamutInterruptedException {
	synchronized(mutex) {
		synchronized(latchAccessMutex) {
			latch = new CountDownLatch(1);
		}
		// instantiation checks whether we doesn't have desired result already, 
		// if not adds itself as a listener to a flag
		Listener listener = new Listener(flag); 
		if (isResult) return result;			
		try {
			latch.await(); // the latch is raised whenever a listener receive a correct result
		} catch (InterruptedException e) {
			throw new PogamutInterruptedException(e, this);
		}
		synchronized(latchAccessMutex) {
			flag.removeListener(listener);
			latch = null;
		}
		return result;
	}
}
 
Example 18
Project: ZooKeeper   File: LeaderElectionSupportTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNodes20() throws IOException, InterruptedException,
    KeeperException {

  int testIterations = 20;
  final CountDownLatch latch = new CountDownLatch(testIterations);
  final AtomicInteger failureCounter = new AtomicInteger();

  for (int i = 0; i < testIterations; i++) {
    runElectionSupportThread(latch, failureCounter);
  }

  Assert.assertEquals(0, failureCounter.get());

  if (!latch.await(10, TimeUnit.SECONDS)) {
    logger
        .info(
            "Waited for all threads to start, but timed out. We had {} failures.",
            failureCounter);
  }
}
 
Example 19
Project: scanning   File: RealQueueTestUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Wait for the given CountDownLatch to countdown or to exceed its timeout
 * (10000ms if no time specified). The noFail argument stops JUnit.fail
 * from being called when the latch is not released.
 */
public static void waitForEvent(CountDownLatch latch, long timeout, Boolean noFail) throws InterruptedException {
	//We may get stuck if the consumer finishes processing faster than the test works through
	//If so, we need to test for a non-empty status set with last bean status equal to our expectation

	//Once finished, check whether the latch was released or timedout
	boolean released = latch.await(timeout, TimeUnit.MILLISECONDS);
	if (released) {
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~\n Final state reached\n~~~~~~~~~~~~~~~~~~~~~~~~~");
	} else {
		System.out.println("#########################\n No final state reported\n#########################");
		if (!noFail) {
			fail("No final state reported");
		}
	}
}
 
Example 20
Project: scanning   File: ResponseConfiguration.java   Source Code and License 6 votes vote down vote up
public void latch(ResponseWaiter waiter) throws EventException, InterruptedException {

		if (waiter==null) waiter = new ResponseWaiter.Dont();

		if (getResponseType()==ResponseType.ONE) {
			this.latch    = new CountDownLatch(1);
			boolean ok = latch.await(timeout, timeUnit);
			while (!ok && waiter.waitAgain()) {
				ok = latch.await(timeout, timeUnit);
			}
			ok = latch.await(timeout, timeUnit); // This is because waitAgain() could be false leaving ok as false, we recheck it!
			if (!ok) throw new EventException("The timeout of "+timeout+" "+timeUnit+" was reached and no response occurred!");

		} else if (getResponseType()==ResponseType.ONE_OR_MORE) {
			somethingFound = false;

			Thread.sleep(timeUnit.toMillis(timeout));
			while (waiter.waitAgain()) {
				Thread.sleep(timeUnit.toMillis(timeout));
			}
			if (!somethingFound) throw new EventException("The timeout of "+timeout+" "+timeUnit+" was reached and no response occurred!");
		}
	}
 
Example 21
Project: athena   File: ObjectiveTrackerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests an event for a host becoming available that matches an intent.
 *
 * @throws InterruptedException if the latch wait fails.
 */

@Test
public void testEventHostAvailableMatch() throws Exception {
    // we will expect 2 delegate calls
    delegate.latch = new CountDownLatch(2);

    Device host = device("host1");
    DeviceEvent deviceEvent = new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, host);
    reasons.add(deviceEvent);

    Key key = Key.of(0x333L, APP_ID);
    Collection<NetworkResource> resources = ImmutableSet.of(host.id());
    tracker.addTrackedResources(key, resources);

    reasons.add(deviceEvent);

    TopologyEvent event = new TopologyEvent(TopologyEvent.Type.TOPOLOGY_CHANGED, topology, reasons);

    listener.event(event);
    assertThat(delegate.latch.await(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS), is(true));
    assertThat(delegate.intentIdsFromEvent, hasSize(1));
    assertThat(delegate.compileAllFailedFromEvent, is(true));
    assertThat(delegate.intentIdsFromEvent.get(0).toString(),
               equalTo("0x333"));
}
 
Example 22
Project: atlas   File: AdditionalActivityManagerNative.java   Source Code and License 6 votes vote down vote up
private synchronized void connectDelegateService(String processName) {
    if(mRemoteDelegate!=null && mRemoteDelegate.asBinder().isBinderAlive()){
        return ;
    }
    mCountDownLatch = new CountDownLatch(1);
    if(targetIntent==null){
        Intent service = new Intent();
        String delegateComponentName = BridgeUtil.getBridgeName(BridgeUtil.TYPE_SERVICEBRIDGE,processName);
        service.setClassName(RuntimeVariables.androidApplication, delegateComponentName);
        targetIntent = service;
    }
    RuntimeVariables.androidApplication.bindService(targetIntent, mDelegateConnection,
            Context.BIND_AUTO_CREATE);
    try {
        mCountDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: azure-documentdb-rxjava   File: DocumentCRUDAsyncAPITest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateDocument_Async() throws Exception {
   
    // create a document
    Document doc = new Document(String.format("{ 'id': 'doc%d', 'counter': '%d'}", 1, 1));
    Observable<ResourceResponse<Document>> createDocumentObservable = asyncClient.createDocument(createdCollection.getSelfLink(), doc, null, true);

    final CountDownLatch doneLatch = new CountDownLatch(1);

    // subscribe to events emitted by the observable
    createDocumentObservable
        .single()           // we know there will be one response
        .subscribe(
            
            documentResourceResponse -> {
                System.out.println(documentResourceResponse.getActivityId());
                doneLatch.countDown();
            },

            error -> {
                System.err.println("an error happened in document creation: actual cause: " + error.getMessage());
            });

    // wait till document creation completes
    doneLatch.await();
}
 
Example 24
Project: guava-mock   File: GeneratedMonitorTest.java   Source Code and License 5 votes vote down vote up
private void enterSatisfyGuardAndLeaveInAnotherThread() {
  final CountDownLatch startedLatch = new CountDownLatch(1);
  startThread(new Runnable() {
    @Override public void run() {
      startedLatch.countDown();
      enterSatisfyGuardAndLeaveInCurrentThread();
    }
  });
  awaitUninterruptibly(startedLatch);
}
 
Example 25
Project: kotlin-late   File: ExecutorServiceRunnerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void runTest() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    runner.run(new Function0<Unit>() {
        @Override
        public Unit invoke() {
            latch.countDown();
            return Unit.INSTANCE;
        }
    });
    latch.await(MEDIUM, TimeUnit.MILLISECONDS);
}
 
Example 26
Project: flume-release-1.7.0   File: TestFileChannelEncryption.java   Source Code and License 5 votes vote down vote up
@Test
public void testThreadedProduce() throws Exception {
  int numThreads = 20;
  Map<String, String> overrides = getOverridesForEncryption();
  overrides.put(FileChannelConfiguration.CAPACITY, String.valueOf(10000));
  overrides.put(FileChannelConfiguration.TRANSACTION_CAPACITY,
      String.valueOf(100));
  channel = createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Executor executor = Executors.newFixedThreadPool(numThreads);
  final AtomicBoolean error = new AtomicBoolean(false);
  final CountDownLatch startLatch = new CountDownLatch(numThreads);
  final CountDownLatch stopLatch = new CountDownLatch(numThreads);
  final Set<String> in = Collections.synchronizedSet(new HashSet<String>());
  for (int i = 0; i < numThreads; i++) {
    executor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          startLatch.countDown();
          startLatch.await();
          in.addAll(putEvents(channel, "thread-produce", 10, 10000, true));
        } catch (Throwable t) {
          error.set(true);
          LOGGER.error("Error in put thread", t);
        } finally {
          stopLatch.countDown();
        }
      }
    });
  }
  stopLatch.await();
  Set<String> out = consumeChannel(channel);

  Assert.assertFalse(error.get());
  compareInputAndOut(in, out);
}
 
Example 27
Project: YZxing   File: DecodeThread.java   Source Code and License 5 votes vote down vote up
DecodeThread(ScannerActivity activity,
             Collection<BarcodeFormat> decodeFormats,
             String characterSet
) {
    this.activity = activity;
    handlerInitLatch = new CountDownLatch(1);
    hints = new EnumMap<>(DecodeHintType.class);
    hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
    if (characterSet != null) {
        hints.put(DecodeHintType.CHARACTER_SET, characterSet);
    }
    hints.put(DecodeHintType.TRY_HARDER, true);
}
 
Example 28
Project: incubator-netbeans   File: ProgressSupportTest.java   Source Code and License 5 votes vote down vote up
public void testDisabledActionDoesNotCauseAnInfiniteLoop() {
    List<ProgressSupport.Action> actions = new ArrayList<ProgressSupport.Action>();

    final CountDownLatch sync = new CountDownLatch(1);
    final AtomicBoolean ran = new AtomicBoolean();

    actions.add(new ProgressSupport.EventThreadAction() {
        public void run(ProgressSupport.Context actionContext) {
            synchronized (sync) {
                ran.set(true);
                sync.countDown();
            }
        }

        public boolean isEnabled() {
            return false;
        }
    });

    RequestProcessor.getDefault().post(new Runnable() {
        public void run() {
            try {
                sync.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {}
            if (!ran.get()) {
                // hmm, anything better?
                System.exit(1);
            }
        }
    });

    ProgressSupport.invoke(actions);
}
 
Example 29
Project: openjdk-jdk10   File: ExchangerTest.java   Source Code and License 5 votes vote down vote up
/**
 * interrupt during wait for exchange throws InterruptedException
 */
public void testExchange_InterruptedException() {
    final Exchanger e = new Exchanger();
    final CountDownLatch threadStarted = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedInterruptedRunnable() {
        public void realRun() throws InterruptedException {
            threadStarted.countDown();
            e.exchange(one);
        }});

    await(threadStarted);
    t.interrupt();
    awaitTermination(t);
}
 
Example 30
Project: hekate   File: StatsdMetricsPublisherTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testQueue() throws Exception {
    int maxQueueSize = StatsdMetricsConfig.DEFAULT_QUEUE_SIZE;

    CountDownLatch resume = new CountDownLatch(1);

    writeDelegate = (db, points, original) -> {
        await(resume);

        original.run();
    };

    publisher.start("test-host", 9999);

    for (int i = 0; i < maxQueueSize * 2; i++) {
        publisher.publish(singleton(new TestMetric("test.metric" + i, i)));
    }

    resume.countDown();

    busyWait("empty queue", () ->
        publisher.queueSize() == 0
    );

    publisher.stop();

    for (int i = 0; i < maxQueueSize; i++) {
        assertEquals("test_host__9999.test.metric" + i + ":" + i + "|g", receiveNext());
    }
}
 
Example 31
Project: elasticsearch_my   File: ScheduleWithFixedDelayTests.java   Source Code and License 5 votes vote down vote up
public void testDoesNotRescheduleUntilExecutionFinished() throws Exception {
    final TimeValue delay = TimeValue.timeValueMillis(100L);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch pauseLatch = new CountDownLatch(1);
    ThreadPool threadPool = mock(ThreadPool.class);
    final Runnable runnable = () ->  {
        // notify that the runnable is started
        startLatch.countDown();
        try {
            // wait for other thread to un-pause
            pauseLatch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    };
    ReschedulingRunnable reschedulingRunnable = new ReschedulingRunnable(runnable, delay, Names.GENERIC, threadPool);
    // this call was made during construction of the runnable
    verify(threadPool, times(1)).schedule(delay, Names.GENERIC, reschedulingRunnable);

    // create a thread and start the runnable
    Thread runThread = new Thread() {
        @Override
        public void run() {
            reschedulingRunnable.run();
        }
    };
    runThread.start();

    // wait for the runnable to be started and ensure the runnable hasn't used the threadpool again
    startLatch.await();
    verifyNoMoreInteractions(threadPool);

    // un-pause the runnable and allow it to complete execution
    pauseLatch.countDown();
    runThread.join();

    // validate schedule was called again
    verify(threadPool, times(2)).schedule(delay, Names.GENERIC, reschedulingRunnable);
}
 
Example 32
Project: XERUNG   File: CropImageActivity.java   Source Code and License 5 votes vote down vote up
private void startCrop() {
    if (isFinishing()) {
        return;
    }
    imageView.setImageRotateBitmapResetBase(rotateBitmap, true);
    CropUtil.startBackgroundJob(this, null, getResources().getString(R.string.crop__wait),
            new Runnable() {
                public void run() {
                    final CountDownLatch latch = new CountDownLatch(1);
                    handler.post(new Runnable() {
                        public void run() {
                            if (imageView.getScale() == 1F) {
                                imageView.center();
                            }
                            latch.countDown();
                        }
                    });
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    new Cropper().crop();
                }
            }, handler
    );
}
 
Example 33
Project: elasticsearch_my   File: ShardStateActionTests.java   Source Code and License 5 votes vote down vote up
public void testNoLongerPrimaryShardException() throws InterruptedException {
    final String index = "test";

    setState(clusterService, ClusterStateCreationUtils.stateWithActivePrimary(index, true, randomInt(5)));

    ShardRouting failedShard = getRandomShardRouting(index);

    AtomicReference<Throwable> failure = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);

    long primaryTerm = clusterService.state().metaData().index(index).primaryTerm(failedShard.id());
    assertThat(primaryTerm, greaterThanOrEqualTo(1L));
    shardStateAction.remoteShardFailed(failedShard.shardId(), failedShard.allocationId().getId(), primaryTerm + 1, "test",
        getSimulatedFailure(), new ShardStateAction.Listener() {
        @Override
        public void onSuccess() {
            failure.set(null);
            latch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            failure.set(e);
            latch.countDown();
        }
    });

    ShardStateAction.NoLongerPrimaryShardException catastrophicError =
            new ShardStateAction.NoLongerPrimaryShardException(failedShard.shardId(), "dummy failure");
    CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear();
    transport.handleRemoteError(capturedRequests[0].requestId, catastrophicError);

    latch.await();
    assertNotNull(failure.get());
    assertThat(failure.get(), instanceOf(ShardStateAction.NoLongerPrimaryShardException.class));
    assertThat(failure.get().getMessage(), equalTo(catastrophicError.getMessage()));
}
 
Example 34
Project: ZooKeeper   File: LeaderElectionSupportTest.java   Source Code and License 5 votes vote down vote up
private Thread runElectionSupportThread(final CountDownLatch latch,
    final AtomicInteger failureCounter, final long sleepDuration) {

  final LeaderElectionSupport electionSupport = createLeaderElectionSupport();

  Thread t = new Thread() {

    @Override
    public void run() {
      try {
        electionSupport.start();
        Thread.sleep(sleepDuration);
        electionSupport.stop();

        latch.countDown();
      } catch (Exception e) {
        logger.warn("Failed to run leader election due to: {}",
            e.getMessage());
        failureCounter.incrementAndGet();
      }
    }
  };

  t.start();

  return t;
}
 
Example 35
Project: https-github.com-apache-zookeeper   File: LearnerSnapshotThrottlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testParallelNoThrottle() throws Exception {
    final int numThreads = 50;

    final LearnerSnapshotThrottler throttler = new LearnerSnapshotThrottler(numThreads);
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    final CountDownLatch threadStartLatch = new CountDownLatch(numThreads);
    final CountDownLatch snapshotProgressLatch = new CountDownLatch(numThreads);

    List<Future<Boolean>> results = new ArrayList<Future<Boolean>>(numThreads);
    for (int i = 0; i < numThreads; i++) {
        results.add(threadPool.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() {
                threadStartLatch.countDown();
                try {
                    threadStartLatch.await();

                    throttler.beginSnapshot(false);

                    snapshotProgressLatch.countDown();
                    snapshotProgressLatch.await();

                    throttler.endSnapshot();
                }
                catch (Exception e) {
                    return false;
                }

                return true;
            }
        }));
    }

    for (Future<Boolean> result : results) {
        Assert.assertTrue(result.get());
    }
}
 
Example 36
Project: Pogamut3   File: Test01_UT2004VisionLocalWorldView_simpleTest.java   Source Code and License 5 votes vote down vote up
@Override
public void run()
{
	try {
		while ( !handler.allFinished() )
		{
			if (failure) throw new RuntimeException("FAILURE DETECTED!");
			List<Thread> thrds = new LinkedList<Thread>();
			for ( TeamedAgentId id : localWorldViews.keySet() )
			{
				if ( handler.cyclesToRun(id) >= 0)
				{
					thrds.add( new EventGenerator(eventsPerCycle, currentTime, localWorldViews.get(id)) );
				}
			}
			latch2 = new CountDownLatch(thrds.size());
			for (Thread t : thrds)
			{
				t.start();
			}
			latch2.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);					
			if (latch2.getCount() > 0 || failure) {
				throw new RuntimeException("FAILURE DETECTED!");
			}
			++currentTime;
			sleep(sleepTime);					
		}
	} catch (Exception e) {
		e.printStackTrace();
		failure = true;
		totalCountDown();	
		return;
	}
	latch.countDown();
}
 
Example 37
Project: cyberduck   File: FSEventWatchService.java   Source Code and License 5 votes vote down vote up
@Override
public WatchKey register(final Watchable folder,
                         final WatchEvent.Kind<?>[] events,
                         final WatchEvent.Modifier... modifiers)
        throws IOException {
    if(log.isInfoEnabled()) {
        log.info(String.format("Register file %s for events %s", folder, Arrays.toString(events)));
    }
    final Pointer[] values = {
            CFStringRef.toCFString(folder.toString()).getPointer()};

    final MacOSXWatchKey key = new MacOSXWatchKey(folder, this, events);

    final double latency = 1.0; // Latency in seconds

    final Map<File, Long> timestamps = createLastModifiedMap(new File(folder.toString()));
    final FSEvents.FSEventStreamCallback callback = new Callback(key, timestamps);
    final FSEventStreamRef stream = library.FSEventStreamCreate(
            Pointer.NULL, callback, Pointer.NULL,
            library.CFArrayCreate(null, values, CFIndex.valueOf(1), null),
            -1, latency,
            kFSEventStreamCreateFlagNoDefer);
    final CountDownLatch lock = new CountDownLatch(1);
    final CFRunLoop loop = new CFRunLoop(lock, stream);
    threadFactory.newThread(loop).start();
    try {
        lock.await();
    }
    catch(InterruptedException e) {
        throw new IOException(String.format("Failure registering for events in %s", folder), e);
    }
    loops.put(key, loop);
    callbacks.put(key, callback);
    return key;
}
 
Example 38
Project: kafka-0.11.0.0-src-with-comment   File: TestFuture.java   Source Code and License 5 votes vote down vote up
public TestFuture() {
    resolved = false;
    getCalledLatch = new CountDownLatch(1);

    resolveOnGet = false;
    resolveOnGetResult = null;
    resolveOnGetException = null;
}
 
Example 39
Project: GitHub   File: JacksonPostObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testObjectListPostRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .build()
                .getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {
                    @Override
                    public void onResponse(List<User> userList) {
                        firstNameRef.set(userList.get(0).firstName);
                        lastNameRef.set(userList.get(0).lastName);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

        assertTrue(latch.await(2, SECONDS));

        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }
 
Example 40
Project: wcs-android-sdk   File: SliceUploadTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnReadFile() throws Exception {
    Log.d(TAG, "testUnReadFile ");
    final CountDownLatch signal = new CountDownLatch(1);
    FileUploader.sliceUpload(null, InstrumentationRegistry.getTargetContext(),
            WcsTestConfig.TOKEN, new File("sfdfo"), null, new SliceUploaderListener() {
                @Override
                public void onSliceUploadSucceed(JSONObject reponseJSON) {
                    Log.d(TAG, "onSuccess: " + reponseJSON);
                    signal.countDown();
                    Assert.assertNull(reponseJSON);
                }

                @Override
                public void onSliceUploadFailured(HashSet<String> errorMessages) {
                    StringBuilder sb = new StringBuilder();
                    for (String string : errorMessages) {
                        sb.append(string + "\r\n");
                        Log.e(TAG, "errorMessage : " + string);
                    }
                    signal.countDown();
                    Assert.assertTrue(sb.toString().contains("file no exists"));
                }

            });
    signal.await(WAIT_TIME, TimeUnit.MILLISECONDS);
}
 
Example 41
Project: GitHub   File: GetObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndObjectGet() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObject(User.class,
                        new OkHttpResponseAndParsedRequestListener<User>() {
                            @Override
                            public void onResponse(Response okHttpResponse, User user) {
                                firstNameRef.set(user.firstName);
                                lastNameRef.set(user.lastName);
                                responseBodySuccess.set(okHttpResponse.isSuccessful());
                                latch.countDown();
                            }

                            @Override
                            public void onError(ANError anError) {
                                assertTrue(false);
                            }
                        });

        assertTrue(latch.await(2, SECONDS));

        assertTrue(responseBodySuccess.get());
        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }
 
Example 42
Project: https-github.com-apache-zookeeper   File: PrepRequestProcessorTest.java   Source Code and License 5 votes vote down vote up
/**
 * It tests that PrepRequestProcessor will return BadArgument KeeperException
 * if the request path (if it exists) is not valid, e.g. empty string.
 */
@Test
public void testInvalidPath() throws Exception {
    pLatch = new CountDownLatch(1);
    processor = new PrepRequestProcessor(zks, new MyRequestProcessor());

    SetDataRequest record = new SetDataRequest("", new byte[0], -1);
    Request req = createRequest(record, OpCode.setData);
    processor.pRequest(req);
    pLatch.await();
    Assert.assertEquals(outcome.getHdr().getType(), OpCode.error);
    Assert.assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
}
 
Example 43
Project: incubator-netbeans   File: ScanUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Checks that task, which signals incomplete data is deferred and is retried again
 * 
 * @throws Exception 
 */
public void testSignalPostJava() throws Exception {
    setupTestFile(false);
    
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicBoolean passed = new AtomicBoolean(false);
    
    CountDownLatch start = new CountDownLatch(1);
    CountDownLatch latch = new CountDownLatch(1);
    
    final ScannerBlock block = new ScannerBlock(start, latch);
    
    IndexingUtils.runAsScanWork(block);
    IndexingManager.getDefault().refreshIndex(testFile1.getParent().getURL(), null);
    
    // wait for the parsing to begin, stop it
    block.start.await();

    Future res = ScanUtils.postUserActionTask(testSource, new Task<CompilationController>() {
        @Override
        public void run(CompilationController parameter) throws Exception {
            count.incrementAndGet();
            ScanUtils.signalIncompleteData(parameter, null);
            passed.set(true);
        }
    });
    // the action should be finished, the error logged, but not thrown
    assertFalse(res.isDone());
    // the task was invoked ONCE
    assertEquals(1, count.intValue());
    
    // free the parser
    block.latch.countDown();
    
    // should not fail !
    res.get(100, TimeUnit.SECONDS);
    
    assertEquals(2, count.intValue());
    assertTrue(passed.get());
}
 
Example 44
Project: fuck_zookeeper   File: SessionTrackerTest.java   Source Code and License 5 votes vote down vote up
/**
 * Verify the session closure request has reached PrepRequestProcessor soon
 * after session expiration by the session tracker
 */
@Test(timeout = 20000)
public void testCloseSessionRequestAfterSessionExpiry() throws Exception {
    ZooKeeperServer zks = setupSessionTracker();

    latch = new CountDownLatch(1);
    zks.sessionTracker.addSession(sessionId, sessionTimeout);
    SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
    SessionImpl sessionImpl = sessionTrackerImpl.sessionsById
            .get(sessionId);
    Assert.assertNotNull("Sessionid:" + sessionId
            + " doesn't exists in sessiontracker", sessionImpl);

    // verify the session existence
    Object sessionOwner = new Object();
    sessionTrackerImpl.checkSession(sessionId, sessionOwner);

    // waiting for the session expiry
    latch.await(sessionTimeout * 2, TimeUnit.MILLISECONDS);

    // Simulating close session request: removeSession() will be executed
    // while OpCode.closeSession
    sessionTrackerImpl.removeSession(sessionId);
    SessionImpl actualSession = sessionTrackerImpl.sessionsById
            .get(sessionId);
    Assert.assertNull("Session:" + sessionId
            + " still exists after removal", actualSession);
}
 
Example 45
Project: redirector   File: SetUpEnvManagerTest.java   Source Code and License 5 votes vote down vote up
private void runTesteeInSeparateThread(Result resultWrapperOutput) throws InterruptedException {
    CountDownLatch setupFinished = new CountDownLatch(1);
    Thread setupThread = new Thread(() -> {
        try {
            testee.setUp();
        } catch (Exception e) {
            log.error("Failed while executing tested method", e);
            resultWrapperOutput.result = false;
        }
        setupFinished.countDown();
    }, "testeeThread");

    setupThread.start();
    setupFinished.await(10, TimeUnit.SECONDS);
}
 
Example 46
Project: incubator-netbeans   File: ParsinApiInteractionTest.java   Source Code and License 5 votes vote down vote up
private ScanTask(
    final CountDownLatch latch,
    final int timeOut,
    final AtomicBoolean resHolder) {
    this.latch = latch;
    this.timeOut = timeOut;
    this.resHolder = resHolder;
}
 
Example 47
Project: azure-documentdb-rxjava   File: DocumentCRUDAsyncAPITest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDocumentCreation_SumUpRequestCharge() throws Exception {
    
    // create 10 documents and sum up all the documents creation request charges

    // create 10 documents
    List<Observable<ResourceResponse<Document>>> listOfCreateDocumentObservables = new ArrayList<>();
    for(int i = 0; i < 10; i++) {
        Document doc = new Document(String.format("{ 'id': 'doc%d', 'counter': '%d'}", i, i));

        Observable<ResourceResponse<Document>> createDocumentObservable = 
                asyncClient.createDocument(createdCollection.getSelfLink(), doc, null, false);
        listOfCreateDocumentObservables.add(createDocumentObservable);
    }
    
    // merge all document creation observables into one observable
    Observable<ResourceResponse<Document>> mergedObservable = Observable.merge(listOfCreateDocumentObservables);
    
    // create a new observable emitting the total charge of creating all 10 documents
    Observable<Double> totalChargeObservable = mergedObservable
            .map(ResourceResponse::getRequestCharge)                //map to request charge
            .reduce((totalCharge, charge) -> totalCharge + charge); //sum up all the charges
    
    final CountDownLatch doneLatch = new CountDownLatch(1);

    // subscribe to the total request charge observable
    totalChargeObservable.subscribe(totalCharge -> {
        // print the total charge
        System.out.println(totalCharge);
        doneLatch.countDown();
    });
    
    doneLatch.await();
}
 
Example 48
Project: android-mobile-engage-sdk   File: IamWebViewProviderTest.java   Source Code and License 5 votes vote down vote up
@Before
public void init() throws NoSuchFieldException, IllegalAccessException {
    injectMobileEngageConfig();
    IamWebViewProvider.webView = null;

    provider = new IamWebViewProvider();
    listener = mock(MessageLoadedListener.class);

    handler = new Handler(Looper.getMainLooper());
    latch = new CountDownLatch(1);
    dummyJsBridge = new IamJsBridge(mock(IamDialog.class), mock(InAppMessageHandlerProvider.class), mock(ButtonClickedRepository.class), "123", mock(Handler.class));
}
 
Example 49
Project: elasticsearch_my   File: BlockClusterStateProcessing.java   Source Code and License 5 votes vote down vote up
@Override
public void stopDisrupting() {
    CountDownLatch latch = disruptionLatch.get();
    if (latch != null) {
        latch.countDown();
    }

}
 
Example 50
Project: guava-mock   File: AbstractListenableFutureTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that all listeners complete, even if they were added before or after
 * the future was finishing.  Also acts as a concurrency test to make sure the
 * locking is done correctly when a future is finishing so that no listeners
 * can be lost.
 */
public void testAllListenersCompleteSuccessfully()
    throws InterruptedException, ExecutionException {

  ExecutorService exec = Executors.newCachedThreadPool();

  int listenerCount = 20;
  final CountDownLatch listenerLatch = new CountDownLatch(listenerCount);

  // Test that listeners added both before and after the value is available
  // get called correctly.
  for (int i = 0; i < 20; i++) {

    // Right in the middle start up a thread to close the latch.
    if (i == 10) {
      new Thread(new Runnable() {
        @Override
        public void run() {
          latch.countDown();
        }
      }).start();
    }

    future.addListener(new Runnable() {
      @Override
      public void run() {
        listenerLatch.countDown();
      }
    }, exec);
  }

  assertSame(Boolean.TRUE, future.get());
  // Wait for the listener latch to complete.
  listenerLatch.await(500, TimeUnit.MILLISECONDS);

  exec.shutdown();
  exec.awaitTermination(500, TimeUnit.MILLISECONDS);
}
 
Example 51
Project: datastreaming-presentation   File: LineSplit.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-linesplit");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

    final StreamsBuilder builder = new StreamsBuilder();

    builder.<String,String>stream("streams-plaintext-input")
           .flatMapValues(value -> Arrays.asList(value.split("\\W+")))
           .to("streams-linesplit-output");


    final Topology topology = builder.build();
    final KafkaStreams streams = new KafkaStreams(topology, props);
    final CountDownLatch latch = new CountDownLatch(1);

    // attach shutdown handler to catch control-c
    Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
        @Override
        public void run() {
            streams.close();
            latch.countDown();
        }
    });

    try {
        streams.start();
        latch.await();
    } catch (Throwable e) {
        System.exit(1);
    }
    System.exit(0);
}
 
Example 52
Project: seraphim   File: SeraphimRemoteCache.java   Source Code and License 5 votes vote down vote up
@Override
public ValueType get(KeyType key) {
    if (key == null) {
        throw new IllegalArgumentException("key cannot be null");
    }

    int callbackId = Seraphim.getHawkings().incrementAndGetId();

    AtomicReference<PacketGetResponse> atomicReference = new AtomicReference<>(null);
    CountDownLatch countDownLatch = new CountDownLatch(1);

    Consumer<PacketGetResponse> consumer = value -> {
        atomicReference.set(value);
        countDownLatch.countDown();
    };

    Seraphim.getHawkings().registerConsumer(consumer);

    PacketGet packet = new PacketGet(callbackId, key);
    this.skyllaClient.sendPacket(packet);

    try {
        countDownLatch.await(500, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    PacketGetResponse response = atomicReference.get();

    if (response == null) {
        return null;
    }

    return (ValueType) response.getValue();
}
 
Example 53
Project: vertx-jooq-async   File: VertxSomethingDaoTest.java   Source Code and License 5 votes vote down vote up
@Test
public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Something something = createSomething();
    dao.insertReturningPrimaryAsync(something)
        .flatMap(id -> dao.insertReturningPrimaryAsync(something.setSomeid(id)))
        .subscribe(
            i -> Assert.fail("Should not happen"),
            err -> {
                Assert.assertEquals(MySQLException.class, err.getClass());
                latch.countDown();
            }
        );
    await(latch);
}
 
Example 54
Project: tangobot   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to block the calling thread until the latch is zeroed by some other task.
 * @param latch Latch to wait for.
 * @param latchName Name to be used in log messages for the given latch.
 */
private void waitForLatchUnlock(CountDownLatch latch, String latchName) {
    try {
        mLog.info("Waiting for " + latchName + " latch release...");
        latch.await();
        mLog.info(latchName + " latch released!");
    } catch (InterruptedException ie) {
        mLog.warn("Warning: continuing before " + latchName + " latch was released");
    }
}
 
Example 55
Project: jdk8u-jdk   File: AnnotationTypeDeadlockTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    CountDownLatch prepareLatch = new CountDownLatch(2);
    AtomicInteger goLatch = new AtomicInteger(1);
    Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
    Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
    taskA.start();
    taskB.start();
    // wait until both threads start-up
    prepareLatch.await();
    // let them go
    goLatch.set(0);
    // obtain ThreadMXBean
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    // wait for threads to finish or dead-lock
    while (taskA.isAlive() || taskB.isAlive()) {
        // attempt to join threads
        taskA.join(500L);
        taskB.join(500L);
        // detect dead-lock
        long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads();
        if (deadlockedIds != null && deadlockedIds.length > 0) {
            StringBuilder sb = new StringBuilder("deadlock detected:\n\n");
            for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) {
                sb.append(ti);
            }
            throw new IllegalStateException(sb.toString());
        }
    }
}
 
Example 56
Project: GitHub   File: MultipartStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndStringMultipart() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final AtomicReference<String> responseStringRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addMultipartParameter("key", "value")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
                    @Override
                    public void onResponse(Response okHttpResponse, String response) {
                        responseBodySuccess.set(okHttpResponse.isSuccessful());
                        responseStringRef.set(response);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

        assertTrue(latch.await(2, SECONDS));

        assertTrue(responseBodySuccess.get());
        assertEquals("data", responseStringRef.get());
    }
 
Example 57
Project: microprofile-fault-tolerance   File: BulkheadAsynchRetryTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test that Retry can be used to prevent receiving Bulkhead exceptions from
 * a method level test. There is enough retrying in the Bean to cover the
 * queue overflow.
 */
@Test()
public void testBulkheadRetryClassAsynchronous55() {
    int iterations = 20;
    int expectedTasksScheduled = iterations;
    int maxSimultaneousWorkers = 5;
    TestData td = new TestData(new CountDownLatch(expectedTasksScheduled));
    Utils.loop(iterations, classBean, maxSimultaneousWorkers, expectedTasksScheduled, td);
    td.check();
}
 
Example 58
Project: FirefoxData-android   File: JSONRecordFetcher.java   Source Code and License 4 votes vote down vote up
public LatchedJSONRecordFetchDelegate(CountDownLatch latch) {
  this.latch = latch;
}
 
Example 59
Project: pooled-jms   File: JmsPoolReconnectOnFailureTest.java   Source Code and License 4 votes vote down vote up
@Ignore("Fails for unknown reason")
@Test(timeout = 60000)
public void testConnectionCanBeCreatedAfterFailure() throws Exception {

    final CountDownLatch failed = new CountDownLatch(1);

    Connection connection = cf.createConnection();
    LOG.info("Fetched new connection from the pool: {}", connection);
    connection.setExceptionListener(new ExceptionListener() {

        @Override
        public void onException(JMSException exception) {
            LOG.info("Pooled Connection failed");
            failed.countDown();
        }
    });

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("test");
    MessageProducer producer = session.createProducer(queue);

    MockJMSConnection mockConnection = (MockJMSConnection) ((JmsPoolConnection) connection).getConnection();
    mockConnection.injectConnectionFailure(new IOException("Lost connection"));

    assertTrue(failed.await(15, TimeUnit.SECONDS));

    try {
        producer.send(session.createMessage());
        fail("Should be disconnected");
    } catch (JMSException ex) {
        LOG.info("Producer failed as expected: {}", ex.getMessage());
    }

    Connection connection2 = cf.createConnection();
    assertNotSame(connection, connection2);
    LOG.info("Fetched new connection from the pool: {}", connection2);
    session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    connection2.close();

    cf.stop();
}
 
Example 60
Project: incubator-netbeans   File: RequestProcessor180386Test.java   Source Code and License 4 votes vote down vote up
@RandomlyFails // NB-Core-Build #8322: hung
    public void testScheduleRepeatingIntervalsAreRoughlyCorrect() throws Exception {
        int runCount = 5;
        final CountDownLatch latch = new CountDownLatch(runCount);
        final List<Long> intervals = Collections.synchronizedList(new ArrayList<Long> (runCount));
//        long initialDelay = 30000;
//        long period = 20000;
//        long fudgeFactor = 4000;
        long initialDelay = 3000;
        long period = 2000;
        long fudgeFactor = 400;
        long expectedInitialDelay = initialDelay - fudgeFactor;
        long expectedPeriod = period - fudgeFactor;
        class C implements Runnable {
            volatile long start = System.currentTimeMillis();
            private int runCount;
            @Override
            public void run() {
                runCount++;
                try {
                    synchronized(this) {
                        long end = System.currentTimeMillis();
                        intervals.add (end - start);
                        start = end;
                    }
                } finally {
                    latch.countDown();
                }
            }
        }
        C c = new C();
        RequestProcessor rp = new RequestProcessor ("testScheduleRepeating", 5, true);
        try {
            Future<?> f = rp.scheduleWithFixedDelay(c, initialDelay, period, TimeUnit.MILLISECONDS);
    //        latch.await(initialDelay + fudgeFactor + ((runCount - 1) * (period + fudgeFactor)), TimeUnit.MILLISECONDS); //XXX
            latch.await();
            f.cancel(true);
            for (int i= 0; i < Math.min(runCount, intervals.size()); i++) {
                long expect = i == 0 ? expectedInitialDelay : expectedPeriod;
                assertTrue ("Expected at least " + expect + " milliseconds before run " + i + " but was " + intervals.get(i), intervals.get(i) >= expect);
            }
            //Ensure we have really exited
            try {
                f.get();
                fail ("CancellationException should have been thrown");
            } catch (CancellationException e) {}
            assertTrue(f.isCancelled());
            assertTrue(f.isDone());
        } finally {
            rp.stop();
        }
    }