Example usage for java.util.concurrent Semaphore Semaphore

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

Introduction

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

Prototype

public Semaphore(int permits) 

Source Link

Document

Creates a Semaphore with the given number of permits and nonfair fairness setting.

Usage

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//  w w w. jav a 2  s  . 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:de.hpi.fgis.hdrs.node.Node.java

Node(Configuration conf, Set<Triple.COLLATION> orders, ArrayList<Peer> peers, Peer localPeer)
        throws IOException {
    this.conf = conf;
    this.segmentConf = new SegmentConfiguration(conf);
    this.orders = orders;
    this.router = new Router(conf, peers, localPeer, this);

    segments = new HashMap<Long, SegmentDescriptor>();

    fileImports = new HashMap<Long, FileImport>();

    transactions = new HashMap<Long, Transaction>();
    transactionMemPool = new Semaphore(conf.getInt(Configuration.KEY_NODE_TRANSACTION_BUFFER,
            Configuration.DEFAULT_NODE_TRANSACTION_BUFFER));

    rootDir = new File(conf.get(Configuration.KEY_ROOT_DIR));
    if (!rootDir.isDirectory()) {
        throw new IOException("hdrs root dir does not exist: " + rootDir);
    }/*ww  w  .  j ava 2 s .c o  m*/
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

private boolean downloadArchive(String filename) throws NetworkException {
    final Semaphore semaphore1 = new Semaphore(0);
    final Semaphore semaphore2 = new Semaphore(0);
    success = false;//from  w ww.  jav a 2s .  co m
    log.setIndeterminate();
    while (true) {
        result = ftpClient.openDataChannel((ActionEvent e) -> {
            if (e.getID() == FtpClient.FTP_OK) {
                try {
                    semaphore1.acquire();
                    InputStream is;
                    is = ((Socket) e.getSource()).getInputStream();
                    downloadedFiles = unTar(is, new File(workingDir));
                    success = true;
                } catch (IOException ex) {
                    Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "Download", ex);
                    log.println("Faild to save file.");
                    ftpClient.closeDataChannel();
                    success = false;
                } catch (ArchiveException | InterruptedException ex) {
                    Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        switch (result) {
        case FtpClient.FTP_OK:
            downloadSize = ftpClient.retr(filename, (ActionEvent e) -> {
                ftpClient.closeDataChannel();
                semaphore2.release();
            });
            if (downloadSize >= 0) {
                if (downloadSize > 1048576) {
                    log.println("~" + Integer.toString(downloadSize / 1048576) + " MB");
                } else if (downloadSize > 1024) {
                    log.println("~" + Integer.toString(downloadSize / 1024) + " kB");
                }
                log.reset();
                log.showPercentage(true);
                log.setMaximum(downloadSize);
                semaphore1.release();
                try {
                    semaphore2.acquire();
                } catch (InterruptedException ex) {
                    return false;
                }
            } else {
                switch (downloadSize) {
                case FtpClient.FTP_NODATA:
                    log.println(
                            "Oops! Server's complaining about missing data channel, although I've opened it.");
                    ftpClient.abandonDataChannel();
                    return false;
                default:
                    ftpClient.abandonDataChannel();
                    return false;
                }
            }
            break;
        case FtpClient.FTP_TIMEOUT:
            if (reconnect()) {
                continue;
            } else {
                return false;
            }
        default:
            return false;
        }

        break;
    }
    return success;
}

From source file:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

@Test
public void shouldReturnIfBackupIsInProgress() throws InterruptedException {
    final Semaphore waitForBackupToBegin = new Semaphore(1);
    final Semaphore waitForAssertion_whichHasToHappen_whileBackupIsRunning = new Semaphore(1);

    Database databaseStrategyMock = mock(Database.class);
    doAnswer((Answer<Object>) invocationOnMock -> {
        waitForBackupToBegin.release();/*w  w  w  .  j a  v  a2  s .  co  m*/
        waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire();
        return null;
    }).when(databaseStrategyMock).backup(any(File.class));

    final BackupService backupService = new BackupService(artifactsDirHolder, goConfigService,
            new TimeProvider(), backupInfoRepository, systemEnvironment, configRepository, databaseStrategyMock,
            null);

    waitForBackupToBegin.acquire();
    Thread thd = new Thread(() -> backupService.startBackup(admin));
    thd.start();

    waitForAssertion_whichHasToHappen_whileBackupIsRunning.acquire();
    waitForBackupToBegin.acquire();
    assertThat(backupService.isBackingUp(), is(true));
    waitForAssertion_whichHasToHappen_whileBackupIsRunning.release();

    thd.join();
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testPostBadHost() throws InterruptedException {
    final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink(
            new ApacheHttpSink.Builder().setUri(URI.create("http://nohost.example.com" + PATH))
                    .setEventHandler(new CompletionHandler(semaphore)),
            logger);// w w  w.  j  a  v  a  2 s. c om

    final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS,
            TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES);

    sink.record(event);
    semaphore.acquire();

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that no data was sent
    _wireMockRule.verify(0, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());

    // Assert that an IOException was captured
    Mockito.verify(logger).error(
            Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="),
            Mockito.any(IOException.class));
}

From source file:com.impetus.ankush2.ganglia.GangliaDeployer.java

private boolean deployNodes(final ClusterConfig conf, Map<String, Map<String, Object>> nodeMap) {
    try {//from   w  ww  .j ava2 s. c o m
        // Node Deployment process ...
        final Semaphore semaphore = new Semaphore(nodeMap.size());
        for (final String host : nodeMap.keySet()) {
            semaphore.acquire();
            AppStoreWrapper.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    conf.getNodes().get(host).setStatus(createNode(host));
                    if (semaphore != null) {
                        semaphore.release();
                    }
                }
            });
        }
        semaphore.acquire(nodeMap.size());
    } catch (Exception e) {
        return addClusterError("There is some exception while deploying " + getComponentName()
                + " on all nodes. " + GangliaConstants.EXCEPTION_STRING, e);
    }
    if (newClusterConf == null) {
        if (!clusterConf.getNodes().get(gmetadHost).getStatus()) {
            logger.error("Could not deploy " + getComponentName() + " on "
                    + GangliaConstants.Ganglia_Services.GangliaMaster + " node , so initializing rollback.",
                    getComponentName());
        }
        return clusterConf.getNodes().get(gmetadHost).getStatus();
    } else {
        return AnkushUtils.getStatus(conf.getNodes());
    }
}

From source file:org.telegram.android.MessagesController.java

public TLRPC.EncryptedChat getEncryptedChatDB(int chat_id) {
    TLRPC.EncryptedChat chat = encryptedChats.get(chat_id);
    if (chat == null) {
        Semaphore semaphore = new Semaphore(0);
        ArrayList<TLObject> result = new ArrayList<>();
        MessagesStorage.getInstance().getEncryptedChat(chat_id, semaphore, result);
        try {/*from w  w  w .ja va  2  s .c  o  m*/
            semaphore.acquire();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        if (result.size() == 2) {
            chat = (TLRPC.EncryptedChat) result.get(0);
            TLRPC.User user = (TLRPC.User) result.get(1);
            putEncryptedChat(chat, false);
            putUser(user, true);
        }
    }
    return chat;
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testHttpClientExecuteException() throws InterruptedException {
    final CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class, invocationOnMock -> {
        throw new NullPointerException("Throw by default");
    });/*from w w  w.  j  a va2 s .c  o  m*/

    final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class);
    final Semaphore semaphore = new Semaphore(0);
    final Sink sink = new ApacheHttpSink(
            new ApacheHttpSink.Builder().setUri(URI.create("http://nohost.example.com" + PATH))
                    .setEventHandler(new CompletionHandler(semaphore)),
            () -> httpClient, logger);

    final TsdEvent event = new TsdEvent(ANNOTATIONS, TEST_EMPTY_SERIALIZATION_TIMERS,
            TEST_EMPTY_SERIALIZATION_COUNTERS, TEST_EMPTY_SERIALIZATION_GAUGES);

    sink.record(event);
    semaphore.acquire();

    // Request matcher
    final RequestPatternBuilder requestPattern = WireMock.postRequestedFor(WireMock.urlEqualTo(PATH))
            .withHeader("Content-Type", WireMock.equalTo("application/octet-stream"));

    // Assert that no data was sent
    _wireMockRule.verify(0, requestPattern);
    Assert.assertTrue(_wireMockRule.findUnmatchedRequests().getRequests().isEmpty());

    // Assert that the runtime exception was captured
    Mockito.verify(logger).error(
            Mockito.startsWith("Encountered failure when sending metrics to HTTP endpoint; uri="),
            Mockito.any(NullPointerException.class));
}

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();/*from www .ja  va2  s .c  o 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.jahia.services.render.filter.cache.AclCacheKeyPartGenerator.java

private Element generateCacheEntry(final String cacheKey, CacheEntryNotFoundCallback callback)
        throws RepositoryException {
    Element element = null;//from  www. j  ava  2  s  .  c  om
    Semaphore semaphore = processings.get(cacheKey);
    if (semaphore == null) {
        semaphore = new Semaphore(1);
        processings.putIfAbsent(cacheKey, semaphore);
    }
    try {
        semaphore.acquire();

        element = cache.get(cacheKey);
        if (element != null) {
            return element;
        }

        logger.debug("Getting ACL for {}", cacheKey);
        long l = System.currentTimeMillis();

        element = new Element(cacheKey, callback.generateCacheEntry());
        element.setEternal(true);
        cache.put(element);
        logger.debug("Getting ACL for {} took {} ms", cacheKey, System.currentTimeMillis() - l);
    } catch (InterruptedException e) {
        logger.debug(e.getMessage(), e);
        Thread.currentThread().interrupt();
    } finally {
        semaphore.release();
    }
    return element;
}