Example usage for java.util.concurrent CountDownLatch await

List of usage examples for java.util.concurrent CountDownLatch await

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch await.

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

From source file:example.springdata.mongodb.people.RxJava2PersonRepositoryIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *//*from ww  w.  ja v  a  2 s . c o  m*/
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    Flowable<Person> people = Flowable.just(new Person("Hank", "Schrader", 43), //
            new Person("Mike", "Ehrmantraut", 62));

    repository.count() //
            .doOnSuccess(System.out::println) //
            .toFlowable() //
            .switchMap(count -> repository.saveAll(people)) //
            .lastElement() //
            .toSingle() //
            .flatMap(v -> repository.count()) //
            .doOnSuccess(System.out::println) //
            .doAfterTerminate(countDownLatch::countDown) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:edu.umn.msi.tropix.proteomics.cagrid.IntegrationTestBase.java

protected boolean pollJob(Job job) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    class Listener implements JobUpdateListener {
        private boolean finishedProperly = false;

        public void jobComplete(final Ticket ticket, final boolean finishedProperly, final Status finalStatus) {
            this.finishedProperly = finishedProperly;
            latch.countDown();//from  w ww .  j av a2 s.c  om
        }

        public void update(final Ticket ticket, final Status status) {
            final QueueStage stage = QueueStage.fromStatusUpdateList(status);
            LOG.info("Queue stage is " + stage.getStageEnumerationValue().getValue());
        }
    }
    final Listener listener = new Listener();
    dListener.setJobUpdateListener(listener);
    jobPoller.pollJob(job);
    latch.await();
    return listener.finishedProperly;
}

From source file:au.org.ala.spatial.analysis.layers.LayerDistanceIndex.java

/**
 * @param threadcount    number of threads to run analysis.
 * @param onlyThesePairs array of distances to run as fieldId1 + " " +
 *                       fieldId2 where fieldId1.compareTo(fieldId2) &lt 0 or null for all missing
 *                       distances.//from ww w . j  a  v  a 2  s .co  m
 * @throws InterruptedException
 */
public void occurrencesUpdate(int threadcount, String[] onlyThesePairs) throws InterruptedException {

    //create distances file if it does not exist.
    File layerDistancesFile = new File(IntersectConfig.getAlaspatialOutputPath() + LAYER_DISTANCE_FILE);
    if (!layerDistancesFile.exists()) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(layerDistancesFile);
            fw.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    Map<String, Double> map = loadDistances();

    LinkedBlockingQueue<String> todo = new LinkedBlockingQueue();

    if (onlyThesePairs != null && onlyThesePairs.length > 0) {
        for (String s : onlyThesePairs) {
            todo.add(s);
        }
    } else {
        //find all environmental layer analysis files
        File root = new File(IntersectConfig.getAlaspatialOutputPath());
        File[] dirs = root.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname != null && pathname.isDirectory();
            }
        });

        HashMap<String, String> domains = new HashMap<String, String>();
        for (File dir : dirs) {
            //iterate through files so we get everything
            File[] files = new File(dir.getPath()).listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".grd") && pathname.getName().startsWith("el");
                }
            });

            for (int i = 0; i < files.length; i++) {
                for (int j = i + 1; j < files.length; j++) {
                    String file1 = files[i].getName().replace(".grd", "");
                    String file2 = files[j].getName().replace(".grd", "");

                    //only operate on file names that are valid fields
                    if (Client.getFieldDao().getFieldById(file1) != null
                            && Client.getFieldDao().getFieldById(file2) != null) {

                        String domain1 = domains.get(file1);
                        if (domain1 == null) {
                            String pid1 = Client.getFieldDao().getFieldById(file1).getSpid();
                            domain1 = Client.getLayerDao().getLayerById(Integer.parseInt(pid1)).getdomain();
                            domains.put(file1, domain1);
                        }
                        String domain2 = domains.get(file2);
                        if (domain2 == null) {
                            String pid2 = Client.getFieldDao().getFieldById(file2).getSpid();
                            domain2 = Client.getLayerDao().getLayerById(Integer.parseInt(pid2)).getdomain();
                            domains.put(file2, domain2);
                        }

                        String key = (file1.compareTo(file2) < 0) ? file1 + " " + file2 : file2 + " " + file1;

                        //domain test
                        if (isSameDomain(parseDomain(domain1), parseDomain(domain2))) {
                            if (!map.containsKey(key) && !todo.contains(key)) {
                                todo.put(key);
                            }
                        }
                    }
                }
            }
        }
    }

    LinkedBlockingQueue<String> toDisk = new LinkedBlockingQueue<String>();
    CountDownLatch cdl = new CountDownLatch(todo.size());
    CalcThread[] threads = new CalcThread[threadcount];
    for (int i = 0; i < threadcount; i++) {
        threads[i] = new CalcThread(cdl, todo, toDisk);
        threads[i].start();
    }

    ToDiskThread toDiskThread = new ToDiskThread(
            IntersectConfig.getAlaspatialOutputPath() + LAYER_DISTANCE_FILE, toDisk);
    toDiskThread.start();

    cdl.await();

    for (int i = 0; i < threadcount; i++) {
        threads[i].interrupt();
    }

    toDiskThread.interrupt();
}

From source file:com.bt.aloha.util.ConcurrentUpdateManagerTest.java

@Test
public void testConcurrentUpdateConflictAwawreGetsCalled() throws Exception {
    // setup//  w w  w . ja  v a 2  s .  co m
    final CountDownLatch firstWriterRead = new CountDownLatch(1);
    final CountDownLatch secondWriterWrote = new CountDownLatch(1);
    final AtomicInteger failuresCounter = new AtomicInteger();

    ConcurrentUpdateBlock concurrentUpdateBlock = new ConflictAwareConcurrentUpdateBlock() {
        public void execute() {
            DialogInfo di = dialogCollection.get(dialogId);
            log.debug("First writer read");
            firstWriterRead.countDown();
            log.debug("Waiting for second writer to write");
            try {
                secondWriterWrote.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            dialogCollection.replace(di);
            log.debug("First writer replaced");
        }

        public String getResourceId() {
            return dialogId;
        }

        public void onConcurrentUpdateConflict() {
            failuresCounter.incrementAndGet();
        }
    };

    Runnable competingWriter = new Runnable() {
        public void run() {
            log.debug("Waiting for first writer to read");
            try {
                firstWriterRead.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DialogInfo di = dialogCollection.get(dialogId);
            dialogCollection.replace(di);
            log.debug("Second writer replaced");
            secondWriterWrote.countDown();
        }
    };

    // act
    new Thread(competingWriter).start();
    concurrentUpdateManager.executeConcurrentUpdate(concurrentUpdateBlock);

    // assert
    assertEquals(1, failuresCounter.get());
}

From source file:com.turo.pushy.apns.ApnsClientBenchmark.java

@Benchmark
@BenchmarkMode(Mode.SingleShotTime)/*  w w w  .ja  va  2 s .  co  m*/
@Threads(1)
@Measurement(iterations = 20, batchSize = 1)
@Warmup(iterations = 20, batchSize = 1)
public long testSendNotifications() throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(this.pushNotifications.size());

    for (final SimpleApnsPushNotification notification : this.pushNotifications) {
        this.client.sendNotification(notification).addListener(
                new GenericFutureListener<Future<PushNotificationResponse<SimpleApnsPushNotification>>>() {

                    @Override
                    public void operationComplete(
                            final Future<PushNotificationResponse<SimpleApnsPushNotification>> future) {
                        if (future.isSuccess()) {
                            countDownLatch.countDown();
                        }
                    }
                });
    }

    countDownLatch.await();
    return countDownLatch.getCount();
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSConnectionPoolImplTest.java

@Test
public void testPoolWithMultipleThreads() {
    String testAppId = "multithreadTestApp";
    /**//from   w  w  w. jav a  2 s . c o  m
     * create 5 threads each sending to 100 devices
     */
    int deviceCount = 100;
    int threadCount = 5;
    Map<String, String> payload = new LinkedHashMap<String, String>(100);
    for (int i = 0; i < deviceCount; i++) {
        payload.put("device:" + (i + 1), "JSON Payload{}:" + (i + 1));
    }
    objectFactory.clearCounter();
    APNSConnectionPoolImpl pool = APNSConnectionPoolImpl.getInstance();
    //initialize the pool with connections for all apps

    //    for (int i = 0; i < appIds.length; i++) {
    //      APNSConnection conn = pool.getConnection(appIds[i], true);
    //      pool.returnConnection(conn);
    //    }

    CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    Executor executor = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
        private AtomicInteger counter = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("TestThread:" + counter.getAndIncrement());
            return t;
        }
    });
    for (int i = 0; i < threadCount; i++) {
        executor.execute(new SimpleAPNSSenderThread(testAppId, true, payload, countDownLatch));
    }
    //wait for the threads to finish
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    int count = objectFactory.getCreatedCount(new APNSConnectionPoolImpl.APNSConnectionKey(testAppId, true));
    assertEquals("Object got created too many times", MAX_OBJECTS_PER_KEY, count);
}

From source file:jef.database.DbUtils.java

/**
 * ?//from w  w w  . ja  v a  2s.co  m
 * 
 * @param tasks
 * @throws SQLException
 */
public static void parallelExecute(List<DbTask> tasks) throws SQLException {
    CountDownLatch latch = new CountDownLatch(tasks.size());
    Queue<SQLException> exceptions = new ConcurrentLinkedQueue<SQLException>();
    Queue<Throwable> throwables = new ConcurrentLinkedQueue<Throwable>();
    for (DbTask task : tasks) {
        task.prepare(latch, exceptions, throwables);
        DbUtils.es.execute(task);
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new SQLException(e);
    }
    if (!exceptions.isEmpty()) {
        throw DbUtils.wrapExceptions(exceptions);
    }
    if (!throwables.isEmpty()) {
        throw DbUtils.toRuntimeException(throwables.peek());
    }
}

From source file:com.uphyca.kitkat.storage.internal.impl.LiveSdkSkyDriveClient.java

@Override
public void initializeIfNecessary() {
    if (mLiveConnectClient != null) {
        return;//from  ww w.j av  a 2  s .  com
    }
    final CountDownLatch lock = new CountDownLatch(1);
    mLiveAuthClient.initialize(SCOPES, new LiveAuthListener() {
        @Override
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                mLiveConnectClient = new LiveConnectClient(session);
            }
            lock.countDown();
        }

        @Override
        public void onAuthError(LiveAuthException exception, Object userState) {
            lock.countDown();
        }
    });
    try {
        lock.await();
    } catch (InterruptedException ignore) {
    }
}

From source file:com.metamx.emitter.core.EmitterTest.java

@Test
public void testTimeBasedEmission() throws Exception {
    final int timeBetweenEmissions = 100;
    emitter = timeBasedEmitter(timeBetweenEmissions);

    final CountDownLatch latch = new CountDownLatch(1);

    httpClient.setGoHandler(new GoHandler() {
        @Override//from  w  w w . j a va2s  .co  m
        public <Intermediate, Final> ListenableFuture<Final> go(Request intermediateFinalRequest,
                HttpResponseHandler<Intermediate, Final> handler) throws Exception {
            latch.countDown();
            return Futures.immediateFuture((Final) okResponse());
        }
    }.times(1));

    long emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 1));

    latch.await();
    long timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(String.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
            timeWaited < timeBetweenEmissions * 2);

    waitForEmission(emitter);

    final CountDownLatch thisLatch = new CountDownLatch(1);
    httpClient.setGoHandler(new GoHandler() {
        @Override
        public <Intermediate, Final> ListenableFuture<Final> go(Request intermediateFinalRequest,
                HttpResponseHandler<Intermediate, Final> handler) throws Exception {
            thisLatch.countDown();
            return Futures.immediateFuture((Final) okResponse());
        }
    }.times(1));

    emitTime = System.currentTimeMillis();
    emitter.emit(new UnitEvent("test", 2));

    thisLatch.await();
    timeWaited = System.currentTimeMillis() - emitTime;
    Assert.assertTrue(String.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
            timeWaited < timeBetweenEmissions * 2);

    waitForEmission(emitter);
    closeNoFlush(emitter);
    Assert.assertTrue("httpClient.succeeded()", httpClient.succeeded());
}

From source file:com.metamx.emitter.core.HttpPostEmitter.java

@Override
public void flush() throws IOException {
    final CountDownLatch latch = new CountDownLatch(1);

    if (started.get()) {

        final EmittingRunnable emittingRunnable = new EmittingRunnable(version.get());
        exec.execute(new Runnable() {
            @Override//  w w w .  j  a  v  a2 s.c o m
            public void run() {
                try {
                    emittingRunnable.run();
                } finally {
                    log.debug("Counting down");
                    latch.countDown();
                }
            }
        });

        try {
            latch.await();
            log.debug("Awaited Latch");
        } catch (InterruptedException e) {
            log.debug("Thread Interrupted");
            Thread.currentThread().interrupt();
        }
    }
}