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.ParseConfigTest.java

@Test
public void testGetInBackgroundWithCallbackFail() throws Exception {
    ParseException exception = new ParseException(ParseException.CONNECTION_FAILED, "error");
    ParseConfigController controller = mockParseConfigControllerWithException(exception);
    ParseCorePlugins.getInstance().registerConfigController(controller);

    final Semaphore done = new Semaphore(0);
    ParseConfig.getInBackground(new ConfigCallback() {
        @Override/*  w  w  w.j av a  2s  .c  om*/
        public void done(ParseConfig config, ParseException e) {
            assertEquals(ParseException.CONNECTION_FAILED, e.getCode());
            assertEquals("error", e.getMessage());
            done.release();
        }
    });

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

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNetSingleUseNoInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*w  ww. j a v a  2  s  . co m*/
                for (int i = 0; i < 2; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    semaphore.release();
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseNoInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*from   w  w  w .j a  v  a2s .  com*/
                for (int i = 0; i < 2; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[8];
                    readFully(socket.getInputStream(), b);
                    semaphore.release();
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(5000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test.1").build());
    handler.handleMessage(MessageBuilder.withPayload("Test.2").build());
    assertTrue(semaphore.tryAcquire(4, 10000, TimeUnit.MILLISECONDS));
    done.set(true);
    ccf.stop();
}

From source file:com.netflix.curator.framework.recipes.shared.TestSharedCount.java

@Test
public void testMultiClients() throws Exception {
    final int CLIENT_QTY = 5;

    List<Future<List<Integer>>> futures = Lists.newArrayList();
    final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>();
    try {// www  . j av  a 2  s.c o  m
        final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY);
        final Semaphore semaphore = new Semaphore(0);
        ExecutorService service = Executors
                .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build());
        for (int i = 0; i < CLIENT_QTY; ++i) {
            Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    final List<Integer> countList = Lists.newArrayList();
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new RetryOneTime(1));
                    clients.add(client);
                    client.start();

                    SharedCount count = new SharedCount(client, "/count", 10);

                    final CountDownLatch latch = new CountDownLatch(1);
                    count.addListener(new SharedCountListener() {
                        @Override
                        public void countHasChanged(SharedCountReader sharedCount, int newCount)
                                throws Exception {
                            if (newCount < 0) {
                                latch.countDown();
                            } else {
                                countList.add(newCount);
                            }

                            semaphore.release();
                        }

                        @Override
                        public void stateChanged(CuratorFramework client, ConnectionState newState) {
                        }
                    });
                    count.start();
                    startLatch.countDown();
                    latch.await();
                    return countList;
                }
            });
            futures.add(future);
        }

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        clients.add(client);
        client.start();

        Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS));

        SharedCount count = new SharedCount(client, "/count", 10);
        count.start();

        List<Integer> countList = Lists.newArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; ++i) {
            Thread.sleep(random.nextInt(10));

            int next = random.nextInt(100);
            countList.add(next);
            count.setCount(next);

            Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS));
        }
        count.setCount(-1);

        for (Future<List<Integer>> future : futures) {
            List<Integer> thisCountList = future.get();
            Assert.assertEquals(thisCountList, countList);
        }
    } finally {
        for (CuratorFramework client : clients) {
            IOUtils.closeQuietly(client);
        }
    }
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNetSingleUseWithInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/*from   w ww  .ja va  2  s  . c o  m*/
                for (int i = 1; i < 3; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (int i = 0; i < 2; i++) {
        Message<?> mOut = channel.receive(10000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    assertTrue(replies.remove("Reply1"));
    assertTrue(replies.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseWithInbound() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                latch.countDown();/* w  w w. ja va  2s  . co  m*/
                for (int i = 1; i < 3; i++) {
                    Socket socket = server.accept();
                    semaphore.release();
                    byte[] b = new byte[6];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.start();
    ccf.setSingleUse(true);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    assertTrue(semaphore.tryAcquire(2, 10000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (int i = 0; i < 2; i++) {
        Message<?> mOut = channel.receive(10000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    assertTrue(replies.remove("Reply1"));
    assertTrue(replies.remove("Reply2"));
    done.set(true);
    ccf.stop();
}

From source file:org.springframework.integration.ip.tcp.TcpSendingMessageHandlerTests.java

@Test
public void testNioSingleUseWithInboundMany() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final Semaphore semaphore = new Semaphore(0);
    final AtomicBoolean done = new AtomicBoolean();
    final List<Socket> serverSockets = new ArrayList<Socket>();
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100);
                latch.countDown();/*w  ww .ja  va 2 s .c  o m*/
                for (int i = 0; i < 100; i++) {
                    Socket socket = server.accept();
                    serverSockets.add(socket);
                    semaphore.release();
                    byte[] b = new byte[9];
                    readFully(socket.getInputStream(), b);
                    b = ("Reply" + i + "\r\n").getBytes();
                    socket.getOutputStream().write(b);
                    socket.close();
                }
                server.close();
            } catch (Exception e) {
                if (!done.get()) {
                    e.printStackTrace();
                }
            }
        }
    });
    AbstractConnectionFactory ccf = new TcpNioClientConnectionFactory("localhost", port);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(10000);
    ccf.setSingleUse(true);
    ccf.setTaskExecutor(Executors.newFixedThreadPool(100));
    ccf.start();
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    int i = 0;
    try {
        for (i = 100; i < 200; i++) {
            handler.handleMessage(MessageBuilder.withPayload("Test" + i).build());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception at " + i);
    }
    assertTrue(semaphore.tryAcquire(100, 20000, TimeUnit.MILLISECONDS));
    Set<String> replies = new HashSet<String>();
    for (i = 100; i < 200; i++) {
        Message<?> mOut = channel.receive(20000);
        assertNotNull(mOut);
        replies.add(new String((byte[]) mOut.getPayload()));
    }
    for (i = 0; i < 100; i++) {
        assertTrue("Reply" + i + " missing", replies.remove("Reply" + i));
    }
    done.set(true);
    ccf.stop();
}

From source file:org.apache.sshd.common.forward.PortForwardingLoadTest.java

@Test
@SuppressWarnings("checkstyle:nestedtrydepth")
public void testLocalForwardingPayload() throws Exception {
    final int numIterations = 100;
    final String payloadTmpData = "This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. ";
    StringBuilder sb = new StringBuilder(payloadTmpData.length() * 1000);
    for (int i = 0; i < 1000; i++) {
        sb.append(payloadTmpData);//w  ww  .ja  va2 s  .  c  o  m
    }
    final String payload = sb.toString();

    Session session = createSession();
    try (ServerSocket ss = new ServerSocket()) {
        ss.setReuseAddress(true);
        ss.bind(new InetSocketAddress((InetAddress) null, 0));
        int forwardedPort = ss.getLocalPort();
        int sinkPort = session.setPortForwardingL(0, TEST_LOCALHOST, forwardedPort);
        final AtomicInteger conCount = new AtomicInteger(0);
        final Semaphore iterationsSignal = new Semaphore(0);
        Thread tAcceptor = new Thread(getCurrentTestName() + "Acceptor") {
            @SuppressWarnings("synthetic-access")
            @Override
            public void run() {
                try {
                    byte[] buf = new byte[8192];
                    log.info("Started...");
                    for (int i = 0; i < numIterations; ++i) {
                        try (Socket s = ss.accept()) {
                            conCount.incrementAndGet();

                            try (InputStream sockIn = s.getInputStream();
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

                                while (baos.size() < payload.length()) {
                                    int l = sockIn.read(buf);
                                    if (l < 0) {
                                        break;
                                    }
                                    baos.write(buf, 0, l);
                                }

                                assertEquals("Mismatched received data at iteration #" + i, payload,
                                        baos.toString());

                                try (InputStream inputCopy = new ByteArrayInputStream(baos.toByteArray());
                                        OutputStream sockOut = s.getOutputStream()) {

                                    while (true) {
                                        int l = sockIn.read(buf);
                                        if (l < 0) {
                                            break;
                                        }
                                        sockOut.write(buf, 0, l);
                                    }
                                }
                            }
                        }
                        log.info("Finished iteration {}", i);
                        iterationsSignal.release();
                    }
                    log.info("Done");
                } catch (Exception e) {
                    log.error("Failed to complete run loop", e);
                }
            }
        };
        tAcceptor.start();
        Thread.sleep(TimeUnit.SECONDS.toMillis(1L));

        byte[] buf = new byte[8192];
        byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < numIterations; i++) {
            log.info("Iteration {}", i);
            try (Socket s = new Socket(TEST_LOCALHOST, sinkPort); OutputStream sockOut = s.getOutputStream()) {

                s.setSoTimeout((int) FactoryManager.DEFAULT_NIO2_MIN_WRITE_TIMEOUT);

                sockOut.write(bytes);
                sockOut.flush();

                try (InputStream sockIn = s.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) {
                    while (baos.size() < payload.length()) {
                        int l = sockIn.read(buf);
                        if (l < 0) {
                            break;
                        }
                        baos.write(buf, 0, l);
                    }
                    assertEquals("Mismatched payload at iteration #" + i, payload, baos.toString());
                }
            } catch (Exception e) {
                log.error("Error in iteration #" + i, e);
            }
        }

        try {
            assertTrue("Failed to await pending iterations=" + numIterations,
                    iterationsSignal.tryAcquire(numIterations, numIterations, TimeUnit.SECONDS));
        } finally {
            session.delPortForwardingL(sinkPort);
        }

        ss.close();
        tAcceptor.join(TimeUnit.SECONDS.toMillis(11L));
    } finally {
        session.disconnect();
    }
}