Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

From source file:my.adam.smo.client.Client.java

public BlockingRpcChannel blockingConnect(final InetSocketAddress sa) {
    return new BlockingRpcChannel() {
        private int countDownCallTimesToRelease = 1;
        private RpcChannel rpc = connect(sa);

        @Override/* w  w  w.ja va  2 s . c  o m*/
        public Message callBlockingMethod(Descriptors.MethodDescriptor method, RpcController controller,
                Message request, Message responsePrototype) throws ServiceException {
            StopWatch stopWatch = new StopWatch("callBlockingMethod");
            stopWatch.start();

            final CountDownLatch callbackLatch = new CountDownLatch(countDownCallTimesToRelease);

            final AtomicReference<Message> result = new AtomicReference<Message>();

            RpcCallback<Message> done = new RpcCallback<Message>() {
                @Override
                public void run(Message parameter) {
                    result.set(parameter);
                    callbackLatch.countDown();
                }
            };

            rpc.callMethod(method, controller, request, responsePrototype, done);
            try {
                boolean succeededBeforeTimeout = callbackLatch.await(blocking_method_call_timeout,
                        TimeUnit.SECONDS);
                if (!succeededBeforeTimeout) {
                    throw new ServiceException(
                            "blocking method timeout reached for method:" + method.getFullName());
                }
            } catch (InterruptedException e) {
                getLogger().error("call failed", e);
                stopWatch.stop();
            }

            stopWatch.stop();
            getLogger().trace(stopWatch.shortSummary());

            return result.get();
        }
    };
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorParticipants.java

@Test
public void testBasic() throws Exception {
    final int SELECTOR_QTY = 10;

    List<LeaderSelector> selectors = Lists.newArrayList();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {// w ww.j  ava 2 s  . com
        client.start();

        final CountDownLatch leaderLatch = new CountDownLatch(1);
        final CountDownLatch workingLatch = new CountDownLatch(SELECTOR_QTY);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                leaderLatch.countDown();
                Thread.currentThread().join();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };

        for (int i = 0; i < SELECTOR_QTY; ++i) {
            LeaderSelector selector = new LeaderSelector(client, "/ls", listener) {
                @Override
                void doWork() throws Exception {
                    workingLatch.countDown();
                    super.doWork();
                }
            };
            selector.setId(Integer.toString(i));
            selectors.add(selector);
        }

        for (LeaderSelector selector : selectors) {
            selector.start();
        }

        Assert.assertTrue(leaderLatch.await(10, TimeUnit.SECONDS));
        Assert.assertTrue(workingLatch.await(10, TimeUnit.SECONDS));

        Thread.sleep(1000); // some time for locks to acquire

        Collection<Participant> participants = selectors.get(0).getParticipants();
        for (int i = 1; i < selectors.size(); ++i) {
            Assert.assertEquals(participants, selectors.get(i).getParticipants());
        }

        Set<String> ids = Sets.newHashSet();
        int leaderCount = 0;
        for (Participant participant : participants) {
            if (participant.isLeader()) {
                ++leaderCount;
            }
            Assert.assertFalse(ids.contains(participant.getId()));
            ids.add(participant.getId());
        }
        Assert.assertEquals(leaderCount, 1);

        Set<String> expectedIds = Sets.newHashSet();
        for (int i = 0; i < SELECTOR_QTY; ++i) {
            expectedIds.add(Integer.toString(i));
        }
        Assert.assertEquals(expectedIds, ids);
    } finally {
        for (LeaderSelector selector : selectors) {
            IOUtils.closeQuietly(selector);
        }
        IOUtils.closeQuietly(client);
    }
}

From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

@Test
public void testReleaseInterrupted() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    SteppableThread latchStepper = new SteppableWaitForLatch(latch);

    interruptInWait(latchStepper, TestMode.RELEASE);

    ((CyclicBarrier) ReflectionTestUtils.getField(latchStepper, "stepStart")).reset();
    latchStepper.start();/*from  w w  w.ja  v  a 2 s .  c  om*/
    latch.countDown();
    latchStepper.releaseAndJoin();
}

From source file:com.googlecode.android_scripting.facade.CameraFacade.java

private void autoFocus(final BooleanResult result, final Camera camera) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    {//from  w  ww . j  a v a 2 s  . c om
        camera.autoFocus(new AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                result.mmResult = success;
                latch.countDown();
            }
        });
        latch.await(10, TimeUnit.SECONDS);
    }
}

From source file:com.microsoft.office.core.FolderAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeFolder();/*from ww w  .  j  a  va2 s  .c o m*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IFolder result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:org.cleverbus.core.common.asynch.msg.MessageOperationServiceTest.java

@Test
public void testRestartForFailedMessage_multiThreaded() throws Exception {
    // prepare message in FAILED state
    final Message[] messages = createAndSaveMessages(1, new MessageProcessor() {
        @Override/*  w  w w. ja  v a2 s  .c  o m*/
        public void process(Message message) {
            message.setState(MsgStateEnum.FAILED);
        }
    });

    // prepare threads
    int threads = 2;
    final CountDownLatch latch = new CountDownLatch(threads);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                // cancel message
                operationService.restartMessage(messages[0].getMsgId(), false);
            } finally {
                latch.countDown();
            }
        }
    };

    // start processing and waits for result
    for (int i = 0; i < threads; i++) {
        new Thread(task).start();
    }

    latch.await();

    // verify
    Message msgDB = em.find(Message.class, messages[0].getMsgId());
    assertThat(msgDB, notNullValue());
    assertThat(msgDB.getState(), is(MsgStateEnum.PARTLY_FAILED));
}

From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java

private void readAndCheck() throws Exception {
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getFolders().getAsync(folder.getId()), new FutureCallback<IFolder>() {
        public void onFailure(Throwable t) {
            reportError(t);/*from w  w w . j a  v a  2  s.c o  m*/
            cdl.countDown();
        }

        public void onSuccess(IFolder result) {
            try {
                folder = result;
                Class<?> cls = folder.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceFolder.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(), getter.invoke(folder));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:ch.cyberduck.core.local.FileWatcher.java

public CountDownLatch register(final Local file, final FileWatcherListener listener) throws IOException {
    // Make sure to canonicalize the watched folder
    final Path folder = new File(file.getParent().getAbsolute()).getCanonicalFile().toPath();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Register folder %s watching for file %s", folder, file));
    }/*from   w  ww .ja  v a 2 s .  c  o m*/
    final WatchKey key = monitor.register(folder,
            new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY });
    if (!key.isValid()) {
        throw new IOException(String.format("Failure registering for events in %s", file));
    }
    final CountDownLatch lock = new CountDownLatch(1);
    pool.execute(new Callable<Boolean>() {
        @Override
        public Boolean call() throws IOException {
            while (true) {
                // wait for key to be signaled
                final WatchKey key;
                try {
                    lock.countDown();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Wait for key from watch service %s", monitor));
                    }
                    key = monitor.take();
                } catch (ClosedWatchServiceException e) {
                    // If this watch service is closed
                    return true;
                } catch (InterruptedException e) {
                    return false;
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Retrieved key %s from watch service %s", key, monitor));
                }
                for (WatchEvent<?> event : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = event.kind();
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Detected file system event %s", kind.name()));
                    }
                    if (kind == OVERFLOW) {
                        log.error(String.format("Overflow event for %s", folder));
                        break;
                    }
                    // The filename is the context of the event. May be absolute or relative path name.
                    if (matches(normalize(LocalFactory.get(folder.toString()), event.context().toString()),
                            LocalFactory.get(folder.toString(), file.getName()))) {
                        callback(LocalFactory.get(folder.toString()), event, listener);
                    } else {
                        log.warn(String.format("Ignored file system event for unknown file %s",
                                event.context()));
                    }
                }
                // Reset the key -- this step is critical to receive further watch events.
                boolean valid = key.reset();
                if (!valid) {
                    // The key is no longer valid and the loop can exit.
                    return true;
                }
            }
        }
    });
    return lock;
}

From source file:de.jackwhite20.japs.shared.nio.NioSocketClient.java

public boolean connect(String host, int port) {

    ChannelFuture channelFuture = new Bootstrap().group(PipelineUtils.newEventLoopGroup(1))
            .channel(PipelineUtils.getChannel()).handler(new ClientChannelInitializer(this))
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT).connect(host, port);

    channelFuture.awaitUninterruptibly();

    channel = channelFuture.channel();//from w  w w  .  j  a va 2s .c o  m

    CountDownLatch countDownLatch = new CountDownLatch(1);

    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            connected = channelFuture.isSuccess();

            countDownLatch.countDown();
        }
    });

    try {
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return connected;
}

From source file:org.wso2.devicemgt.raspberry.agent.SidhdhiQuery.java

/**
 * Make http call to specified endpoint with events
 * @param inEvents/* w  w w . jav  a 2 s. c om*/
 * @param bulbEP
 * @param logText
 */
private void performHTTPCall(Event[] inEvents, String bulbEP, String logText) {
    if (inEvents != null && inEvents.length > 0) {
        EventPrinter.print(inEvents);
        String url = constants.prop.getProperty(bulbEP);

        CloseableHttpAsyncClient httpclient = null;

        httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        HttpGet request = new HttpGet(url);
        log.info("Bulb Status : " + logText);
        final CountDownLatch latch = new CountDownLatch(1);
        Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse httpResponse) {
                latch.countDown();
            }

            @Override
            public void failed(Exception e) {
                latch.countDown();
            }

            @Override
            public void cancelled() {
                latch.countDown();
            }
        });

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}