Example usage for java.util.concurrent Semaphore release

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

Introduction

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

Prototype

public void release() 

Source Link

Document

Releases a permit, returning it to the semaphore.

Usage

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

@Test
public void testHttpClientSupplierException() throws InterruptedException, IOException {
    final org.slf4j.Logger logger = Mockito.mock(org.slf4j.Logger.class);
    final Semaphore semaphore = new Semaphore(0);
    final ApacheHttpSinkEventHandler handler = Mockito.mock(ApacheHttpSinkEventHandler.class);
    final Sink sink = new ApacheHttpSink(new ApacheHttpSink.Builder()
            .setUri(URI.create("http://nohost.example.com" + PATH)).setEventHandler(handler), () -> {
                semaphore.release();
                throw new IllegalStateException("Test Exception");
            }, logger);//from w  w w.j  av a2 s.  co  m

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

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

    // Assert that the runtime exception was captured
    Mockito.verify(logger, Mockito.timeout(1000)).error(
            Mockito.startsWith("MetricsSinkApacheHttpWorker failure"),
            Mockito.any(IllegalStateException.class));

    // 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());

    // Verify no handler was invoked
    Mockito.verify(handler, Mockito.never()).attemptComplete(Mockito.anyLong(), Mockito.anyLong(),
            Mockito.anyBoolean(), Mockito.any(Quantity.class));
}

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

/**
 * Have both cache1 and cache2 do add and commit. cache1 commit should time
 * out since it can't obtain the lock when trying to replicate cache2. On the
 * other hand, cache2 commit will succeed since now that cache1 is rollbacked
 * and lock is released./*from  ww  w. j  a v a2 s.  c o  m*/
 */
public void testPutTx1() throws Exception {
    final CacheSPI<Object, Object> c1 = this.cache1;

    final Semaphore threadOneFirstPart = new Semaphore(0);
    final Semaphore threadTwoFirstPart = new Semaphore(0);
    final Semaphore threadOneSecondPart = new Semaphore(0);

    Thread t1 = new Thread() {
        public void run() {
            TransactionManager tm;

            try {
                tm = beginTransaction();
                c1.put("/a/b/c", "age", 38);
                c1.put("/a/b/c", "age", 39);
                threadOneFirstPart.release();

                threadTwoFirstPart.acquire();
                try {
                    tm.commit();
                } catch (RollbackException ex) {
                } finally {
                    threadOneSecondPart.release();
                }
            } catch (Throwable ex) {
                ex.printStackTrace();
                t1_ex = ex;
            }
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            TransactionManager tm;

            try {
                threadOneFirstPart.acquire();
                tm = beginTransaction();
                assertNull(cache2.get("/a/b/c", "age"));// must be null as not yet
                                                        // committed
                cache2.put("/a/b/c", "age", 40);

                threadTwoFirstPart.release();

                threadOneSecondPart.acquire();
                assertEquals(40, cache2.get("/a/b/c", "age"));// must not be null
                tm.commit();

                tm = beginTransaction();
                assertEquals("After cache2 commit", 40, cache2.get("/a/b/c", "age"));
                tm.commit();
            } catch (Throwable ex) {
                ex.printStackTrace();
                t2_ex = ex;
            } finally {
                lock.release();
            }
        }
    };

    // Let the game start
    t1.start();
    t2.start();

    t1.join();
    t2.join();

    if (t1_ex != null) {
        fail("Thread1 failed: " + t1_ex);
    }
    if (t2_ex != null) {
        fail("Thread2 failed: " + t2_ex);
    }
}

From source file:org.commoncrawl.service.parser.client.ParserNode.java

public ParseResult dispatchRequest(final ParseRequest request) throws IOException {
    final AtomicReference<ParseResult> result = new AtomicReference<ParseResult>();

    if (_online.get()) {
        //      LOG.info("Dispatching Parse Request for URL:" + request.getDocURL() 
        //          + " to Node:" + _nodeName);  
        final Semaphore requestSemaphore = new Semaphore(0);

        _eventLoop.queueAsyncCallback(new org.commoncrawl.async.Callback() {

            @Override//from w  ww .ja  v a 2  s . c  om
            public void execute() {
                try {
                    _asyncStub.parseDocument(request, new Callback<ParseRequest, ParseResult>() {

                        @Override
                        public void requestComplete(AsyncRequest<ParseRequest, ParseResult> request) {
                            try {
                                //                  LOG.info("Parse Request for URL:" + request.getInput().getDocURL() 
                                //                      + " recvd responseStatus:" + request.getStatus() 
                                //                      + " from Node:" + _nodeName); 

                                if (request.getStatus() == Status.Success) {
                                    result.set(request.getOutput());
                                }
                            } finally {
                                //                  LOG.info("Releasing Request Semaphore for URL:" + request.getInput().getDocURL());
                                requestSemaphore.release();
                            }
                        }
                    });
                } catch (Exception e) {
                    LOG.error(CCStringUtils.stringifyException(e));
                    LOG.info("Releasing Request Semaphore for URL:" + request.getDocURL());
                    requestSemaphore.release();
                }
            }
        });

        //      LOG.info("Waiting on ParseReq Semaphore for URL:"+ request.getDocURL());
        requestSemaphore.acquireUninterruptibly();
        //      LOG.info("ParseReq Semaphore signlaed for URL:"+ request.getDocURL());
    }
    return result.get();
}

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 .ja  va 2 s .  c  o m
    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;
}

From source file:org.apache.pulsar.broker.service.BrokerService.java

/**
 * It creates a topic async and returns CompletableFuture. It also throttles down configured max-concurrent topic
 * loading and puts them into queue once in-process topics are created.
 * /* www .  j av  a2  s. co m*/
 * @param topic persistent-topic name
 * @return CompletableFuture<Topic>
 * @throws RuntimeException
 */
protected CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException {
    checkTopicNsOwnership(topic);

    final CompletableFuture<Topic> topicFuture = new CompletableFuture<>();

    final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get();

    if (topicLoadSemaphore.tryAcquire()) {
        createPersistentTopic(topic, topicFuture);
        topicFuture.handle((persistentTopic, ex) -> {
            // release permit and process pending topic
            topicLoadSemaphore.release();
            createPendingLoadTopic();
            return null;
        });
    } else {
        pendingTopicLoadingQueue.add(new ImmutablePair<String, CompletableFuture<Topic>>(topic, topicFuture));
        if (log.isDebugEnabled()) {
            log.debug("topic-loading for {} added into pending queue", topic);
        }
    }
    return topicFuture;
}

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

@Test
public void shouldNotReloadScheduledJobPlansWhenAgentWorkAssignmentIsInProgress() throws Exception {
    fixture.createPipelineWithFirstStageScheduled();
    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);
    JobInstance job = pipeline.getFirstStage().getJobInstances().first();

    final JobInstanceService mockJobInstanceService = mock(JobInstanceService.class);

    final Pipeline pipeline1 = pipeline;
    final Semaphore sem = new Semaphore(1);
    sem.acquire();/*from  w  ww  .  ja v a2 s .  c o  m*/
    when(mockJobInstanceService.orderedScheduledBuilds())
            .thenReturn(jobInstanceService.orderedScheduledBuilds());
    when(mockJobInstanceService.buildByIdWithTransitions(job.getId()))
            .thenReturn(jobInstanceService.buildByIdWithTransitions(job.getId()));

    ScheduledPipelineLoader scheduledPipelineLoader = new ScheduledPipelineLoader(null, null, null, null, null,
            null, null, null) {
        @Override
        public Pipeline pipelineWithPasswordAwareBuildCauseByBuildId(long buildId) {
            sem.release();
            sleepQuietly(1000);
            verify(mockJobInstanceService, times(1)).orderedScheduledBuilds();
            return pipeline1;
        }
    };

    final BuildAssignmentService buildAssignmentServiceUnderTest = new BuildAssignmentService(goConfigService,
            mockJobInstanceService, scheduleService, agentService, environmentConfigService,
            transactionTemplate, scheduledPipelineLoader, pipelineService, builderFactory,
            maintenanceModeService, elasticAgentPluginService, systemEnvironment, secretParamResolver,
            jobStatusTopic, consoleService);

    final Throwable[] fromThread = new Throwable[1];
    buildAssignmentServiceUnderTest.onTimer();

    Thread assigner = new Thread(() -> {
        try {
            final AgentConfig agentConfig = AgentMother.localAgentWithResources("some-other-resource");

            buildAssignmentServiceUnderTest.assignWorkToAgent(agent(agentConfig));
        } catch (Throwable e) {
            e.printStackTrace();
            fromThread[0] = e;
        } finally {

        }
    }, "assignmentThread");
    assigner.start();

    sem.acquire();
    buildAssignmentServiceUnderTest.onTimer();

    assigner.join();
    assertThat(fromThread[0], is(nullValue()));
}

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

private boolean deployNodes(final ClusterConfig conf, Map<String, Map<String, Object>> nodeMap) {
    try {/*w  w  w .j  av  a 2 s  .c  om*/
        // 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:com.impetus.ankush2.ganglia.GangliaDeployer.java

@Override
public boolean unregister(final ClusterConfig conf) {

    try {//from ww w.  jav  a  2 s. c o  m
        if (String.valueOf(advanceConf.get(Constant.Keys.REGISTER_LEVEL))
                .equalsIgnoreCase(Constant.RegisterLevel.LEVEL1.toString())) {
            return true;
        }

        if (!initializeDataMembers(conf)) {
            return false;
        }
        final String infoMsg = "Unregistering " + getComponentName() + "...";
        logger.info(infoMsg, getComponentName());
        // Getting node map for cluster deployment
        Map<String, Map<String, Object>> nodeMap = new HashMap<String, Map<String, Object>>(
                compConfig.getNodes());

        // Node Registration 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(unregisterNode(host));
                    if (semaphore != null) {
                        semaphore.release();
                    }
                }
            });
        }
        semaphore.acquire(nodeMap.size());

        // Return false if any of the node is not deployed.
        return AnkushUtils.getStatus(conf.getNodes());
    } catch (Exception e) {
        logger.error(e.getMessage());
        return false;
    }
}

From source file:com.bt.aloha.collections.memory.InMemoryCollectionImpl.java

public T get(String infoId) {
    if (infoId == null)
        throw new IllegalArgumentException("Info id must not be null");

    Semaphore semaphore = getSemaphores().get(infoId);
    if (semaphore == null) {
        log.debug(String.format("No info object for %s in %s, returning null ", infoId,
                this.getClass().getSimpleName()));
        return null;
    }//w  ww . j  ava 2  s  .c o m
    // log.debug("semaphores.size: " + getSemaphores().size());
    // log.debug("infos.size: " + infos.size());
    // log.debug("semaphore: " + semaphore.toString());

    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        log.error(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId, this.getClass().getSimpleName(),
                e.getMessage()));
        throw new CollectionAccessInterruptedException(String.format(FAILED_TO_READ_OBJECT_MESSAGE, infoId,
                this.getClass().getSimpleName(), e.getMessage()), e);
    }
    try {
        if (infos.containsKey(infoId)) {
            T result = (T) infos.get(infoId).cloneObject();
            log.debug(String.format("Retrieved info %s with version %s", infoId, result.getVersionId()));
            return (T) result;
        }
        log.debug(String.format("No info object for %s in %s, returning null ", infoId,
                this.getClass().getSimpleName()));
        return null;
    } finally {
        semaphore.release();
    }
}