Example usage for java.util.concurrent Semaphore tryAcquire

List of usage examples for java.util.concurrent Semaphore tryAcquire

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore tryAcquire.

Prototype

public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Acquires the given number of permits from this semaphore, if all become available within the given waiting time and the current thread has not been Thread#interrupt interrupted .

Usage

From source file:com.parse.ParsePushTest.java

@Test
public void testUnsubscribeInBackgroundWithCallbackFail() throws Exception {
    ParsePushChannelsController controller = mock(ParsePushChannelsController.class);
    final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
    when(controller.unsubscribeInBackground(anyString())).thenReturn(Task.<Void>forError(exception));
    ParseCorePlugins.getInstance().registerPushChannelsController(controller);

    ParsePush push = new ParsePush();
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    push.unsubscribeInBackground("test", new SaveCallback() {
        @Override// w  w w  . ja v  a 2s  . c  om
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });
    assertSame(exception, exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    verify(controller, times(1)).unsubscribeInBackground("test");
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testIssue27Alt() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from   w  w w .j  a  v a  2s .c  o m
    try {
        client.create().forPath("/base");
        client.create().forPath("/base/a");
        client.create().forPath("/base/b");
        client.create().forPath("/base/c");

        client.getChildren().forPath("/base");

        final List<PathChildrenCacheEvent.Type> events = Lists.newArrayList();
        final Semaphore semaphore = new Semaphore(0);
        PathChildrenCache cache = new PathChildrenCache(client, "/base", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                events.add(event.getType());
                semaphore.release();
            }
        });
        cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);

        client.delete().forPath("/base/a");
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));

        client.create().forPath("/base/a");
        Assert.assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS));

        List<PathChildrenCacheEvent.Type> expected = Lists.newArrayList(
                PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED);
        Assert.assertEquals(expected, events);
    } finally {
        client.close();
    }
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSendInBackgroundWithCallbackSuccess() throws Exception {
    // Mock controller
    ParsePushController controller = mock(ParsePushController.class);
    when(controller.sendInBackground(any(ParsePush.State.class), anyString()))
            .thenReturn(Task.<Void>forResult(null));
    ParseCorePlugins.getInstance().registerPushController(controller);

    // Make sample ParsePush data and call method
    ParsePush push = new ParsePush();
    JSONObject data = new JSONObject();
    data.put("key", "value");
    List<String> channels = new ArrayList<>();
    channels.add("test");
    channels.add("testAgain");
    push.builder.expirationTime((long) 1000).data(data).pushToIOS(true).channelSet(channels);
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    push.sendInBackground(new SendCallback() {
        @Override//from ww  w  .j  ava2  s . c o  m
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });

    // Make sure controller is executed and state parameter is correct
    assertNull(exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class);
    verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString());
    ParsePush.State state = stateCaptor.getValue();
    assertTrue(state.pushToIOS());
    assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE);
    assertEquals(2, state.channelSet().size());
    assertTrue(state.channelSet().contains("test"));
    assertTrue(state.channelSet().contains("testAgain"));
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSendInBackgroundWithCallbackFail() throws Exception {
    // Mock controller
    ParsePushController controller = mock(ParsePushController.class);
    final ParseException exception = new ParseException(ParseException.OTHER_CAUSE, "error");
    when(controller.sendInBackground(any(ParsePush.State.class), anyString()))
            .thenReturn(Task.<Void>forError(exception));
    ParseCorePlugins.getInstance().registerPushController(controller);

    // Make sample ParsePush data and call method
    ParsePush push = new ParsePush();
    JSONObject data = new JSONObject();
    data.put("key", "value");
    List<String> channels = new ArrayList<>();
    channels.add("test");
    channels.add("testAgain");
    push.builder.expirationTime((long) 1000).data(data).pushToIOS(true).channelSet(channels);
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    push.sendInBackground(new SendCallback() {
        @Override/*from  w  w  w .  j  av a2s  . c om*/
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });

    // Make sure controller is executed and state parameter is correct
    assertSame(exception, exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class);
    verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString());
    ParsePush.State state = stateCaptor.getValue();
    assertTrue(state.pushToIOS());
    assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE);
    assertEquals(2, state.channelSet().size());
    assertTrue(state.channelSet().contains("test"));
    assertTrue(state.channelSet().contains("testAgain"));
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSendDataInBackgroundWithCallback() throws Exception {
    // Mock controller
    ParsePushController controller = mock(ParsePushController.class);
    when(controller.sendInBackground(any(ParsePush.State.class), anyString()))
            .thenReturn(Task.<Void>forResult(null));
    ParseCorePlugins.getInstance().registerPushController(controller);

    // Make sample ParsePush data and call method
    JSONObject data = new JSONObject();
    data.put("key", "value");
    data.put("keyAgain", "valueAgain");
    ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
    query.getBuilder().whereEqualTo("foo", "bar");
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    ParsePush.sendDataInBackground(data, query, new SendCallback() {
        @Override//  ww  w  .j  a  v  a 2s .  co  m
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });

    // Make sure controller is executed and state parameter is correct
    assertNull(exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class);
    verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString());
    ParsePush.State state = stateCaptor.getValue();
    // Verify query state
    ParseQuery.State<ParseInstallation> queryState = state.queryState();
    JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get());
    assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo"));
    // Verify data
    assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE);
}

From source file:com.parse.ParsePushTest.java

@Test
public void testSendMessageInBackgroundWithCallback() throws Exception {
    // Mock controller
    ParsePushController controller = mock(ParsePushController.class);
    when(controller.sendInBackground(any(ParsePush.State.class), anyString()))
            .thenReturn(Task.<Void>forResult(null));
    ParseCorePlugins.getInstance().registerPushController(controller);

    // Make sample ParsePush data and call method
    ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
    query.getBuilder().whereEqualTo("foo", "bar");
    final Semaphore done = new Semaphore(0);
    final Capture<Exception> exceptionCapture = new Capture<>();
    ParsePush.sendMessageInBackground("test", query, new SendCallback() {
        @Override/*  w  w  w  .  ja  v a  2  s. c o m*/
        public void done(ParseException e) {
            exceptionCapture.set(e);
            done.release();
        }
    });

    // Make sure controller is executed and state parameter is correct
    assertNull(exceptionCapture.get());
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class);
    verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString());
    ParsePush.State state = stateCaptor.getValue();
    // Verify query state
    ParseQuery.State<ParseInstallation> queryState = state.queryState();
    JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get());
    assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo"));
    // Verify message
    assertEquals("test", state.data().getString(ParsePush.KEY_DATA_MESSAGE));
}

From source file:org.novelang.outfit.shell.ProcessShell.java

protected final void start(final long timeout, final TimeUnit timeUnit)
        throws IOException, InterruptedException, ProcessCreationException {
    final Semaphore startupSemaphore = new Semaphore(0);

    LOGGER.info("Starting process ", getNickname(), " in directory '", workingDirectory.getAbsolutePath(),
            "'...");
    LOGGER.info("Arguments: ", processArguments);

    synchronized (stateLock) {

        ensureInState(State.READY);
        process = new ProcessBuilder().command(processArguments).directory(workingDirectory).start();

        standardStreamWatcherThread = new Thread(threadGroup,
                createStandardOutputWatcher(process.getInputStream(), startupSemaphore),
                "standardWatcher-" + nickname);

        errorStreamWatcherThread = new Thread(threadGroup, createErrorOutputWatcher(process.getErrorStream()),
                "errorWatcher-" + nickname);

        standardStreamWatcherThread.setDaemon(true);
        standardStreamWatcherThread.start();
        errorStreamWatcherThread.setDaemon(true);
        errorStreamWatcherThread.start();

        LOGGER.debug("Waiting for startup sensor to detect startup line...");

        startupSemaphore.tryAcquire(1, timeout, timeUnit);

        if (state == State.BROKEN) {
            throw new ProcessCreationException("Couldn't create " + getNickname());
        } else {/* w  ww  .  ja  v  a  2  s.c  o m*/
            state = State.RUNNING;
        }
    }

    LOGGER.info("Successfully launched process: ", getNickname(), " (it may be initializing now).");
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testOverSubscribed() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    ExecutorService service = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(service);
    try {//from  w  w w .  j  a  v  a 2  s  .co  m
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch latch = new CountDownLatch(1);
        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) {
                        @Override
                        protected List<String> getChildrenForEntering() throws Exception {
                            semaphore.release();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            return super.getChildrenForEntering();
                        }
                    };
                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));
                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    return null;
                }
            });
        }

        Assert.assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter
        latch.countDown();

        for (int i = 0; i < (QTY + 1); ++i) {
            completionService.take().get(); // to check for assertions
        }
    } finally {
        service.shutdown();
        IOUtils.closeQuietly(client);
    }
}

From source file:org.apache.spark.network.RpcIntegrationSuite.java

private RpcResult sendRPC(String... commands) throws Exception {
    TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
    final Semaphore sem = new Semaphore(0);

    final RpcResult res = new RpcResult();
    res.successMessages = Collections.synchronizedSet(new HashSet<String>());
    res.errorMessages = Collections.synchronizedSet(new HashSet<String>());

    RpcResponseCallback callback = new RpcResponseCallback() {
        @Override//from ww w .  jav  a  2s  .c  o  m
        public void onSuccess(ByteBuffer message) {
            String response = JavaUtils.bytesToString(message);
            res.successMessages.add(response);
            sem.release();
        }

        @Override
        public void onFailure(Throwable e) {
            res.errorMessages.add(e.getMessage());
            sem.release();
        }
    };

    for (String command : commands) {
        client.sendRpc(JavaUtils.stringToBytes(command), callback);
    }

    if (!sem.tryAcquire(commands.length, 5, TimeUnit.SECONDS)) {
        fail("Timeout getting response from the server");
    }
    client.close();
    return res;
}

From source file:com.parse.ParseConfigTest.java

@Test
public void testGetInBackgroundWithCallbackSuccess() throws Exception {
    final Map<String, Object> params = new HashMap<>();
    params.put("string", "value");

    ParseConfig config = new ParseConfig(params);
    ParseConfigController controller = mockParseConfigControllerWithResponse(config);
    ParseCorePlugins.getInstance().registerConfigController(controller);

    final Semaphore done = new Semaphore(0);
    ParseConfig.getInBackground(new ConfigCallback() {
        @Override/*from  w ww .  j a  v a  2 s. co  m*/
        public void done(ParseConfig config, ParseException e) {
            assertEquals(1, config.params.size());
            assertEquals("value", config.params.get("string"));
            done.release();
        }
    });

    // Make sure the callback is called
    assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
    verify(controller, times(1)).getAsync(anyString());
}