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:fr.xebia.management.statistics.ServiceStatistics.java

@ManagedAttribute
public void setMaxActive(int maxActive) {
    if (maxActive > 0) {
        this.maxActiveSemaphore = new Semaphore(maxActive);
    } else {/*from w  ww  . j a v  a 2 s  . co  m*/
        this.maxActiveSemaphore = null;
    }
}

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

@Test
public void testIssue27() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from w  ww.  j a va  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();

        Assert.assertTrue(semaphore.tryAcquire(3, 10, TimeUnit.SECONDS));

        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_ADDED,
                PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED,
                PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED);
        Assert.assertEquals(expected, events);
    } finally {
        client.close();
    }
}

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

@Override
public boolean start(final ClusterConfig conf, Collection<String> nodes) {
    final Semaphore semaphore = new Semaphore(nodes.size());
    String gangliaMaster = (String) advanceConf.get(GangliaConstants.ClusterProperties.GMETAD_HOST);
    try {/*  w ww .j  a  va2  s .  c o m*/
        // starting Ganglia master during deployment case
        if (newClusterConf == null) {
            // starting ganglia master first and then applying a 1 minute
            // sleep
            // before starting gmond
            if (!startGangliaMaster(gangliaMaster)) {
                return false;
            }
        }

        // starting service in each cluster node
        for (final String host : nodes) {
            semaphore.acquire();
            AppStoreWrapper.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    conf.getNodes().get(host).setStatus(startGmond(host));
                    if (semaphore != null) {
                        semaphore.release();
                    }
                }
            });
        }
        semaphore.acquire(nodes.size());
    } catch (Exception e) {
        logger.warn("There is some exception while stating " + getComponentName() + " services.",
                getComponentName(), e);
    }
    // Return false if any of the node service is not started.
    // return AnkushUtils.getStatus(conf.getNodes());
    return true;
}

From source file:org.mahasen.node.MahasenNodeManager.java

/**
 * @param id//  www .jav a  2 s . c o m
 */
public void deleteContent(final Id id) {

    final Semaphore control = new Semaphore(0);

    Continuation continuation = new Continuation() {

        public void receiveResult(Object result) {
            if (result instanceof MahasenPastContent) {
                System.out.println(" recieved result for " + ((MahasenPastContent) result).getId());

            }
        }

        public void receiveException(Exception result) {
            result.printStackTrace();
        }
    };

    mahasenPastApp.delete(id, continuation);
    control.release();
}

From source file:s3.S3JFrame.java

private String getMediaCallId(String sipAddress) {
    String mediaCallId = this.mediaCallIds.get(sipAddress);
    CallState callState = null;//  w w  w .ja  v  a 2  s  .com
    if (mediaCallId != null)
        callState = callBean.getCallInformation(mediaCallId).getCallState();

    if (null == mediaCallId || CallState.Terminated.equals(callState)) {
        this.callConnectedSemaphore = new Semaphore(0);
        mediaCallId = mediaCallBean.createMediaCall(getDialogId(sipAddress));
        this.waitForCallConnectedEvent();
        this.mediaCallIds.put(sipAddress, mediaCallId);
    }
    return mediaCallId;
}

From source file:org.marketcetera.saclient.SAClientWSTest.java

private static <R> void verifyInvocationCannotBeInterrupted(final WSTester<R> inTester) throws Exception {
    resetServiceParameters();//from w ww.  j  a v a  2 s. c o m
    getMockSAService().setSleep(true);
    inTester.setReturnValue(false);
    final Semaphore sema = new Semaphore(0);
    final AtomicReference<Exception> interruptFailure = new AtomicReference<Exception>();
    Thread t = new Thread() {
        @Override
        public void run() {
            sema.release();
            try {
                inTester.invokeApi(false);
            } catch (Exception ex) {
                interruptFailure.set(ex);
            }
        }
    };
    t.start();
    //Wait for the thread to be started
    sema.acquire();
    //Interrupt it as soon as it is found started
    t.interrupt();
    //wait for it to end
    t.join();
    //verify that we are not able to interrupt it
    assertNull("API invocation got interrupted!", interruptFailure.get());
}

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.j a  v  a2s  . c  o m
        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:org.jpac.JPac.java

protected JPac() {
    super();//from www.  ja v  a2 s .  c  om
    setName(getClass().getSimpleName());

    tracePoint = 0;
    minRemainingCycleTime = Long.MAX_VALUE;
    maxRemainingCycleTime = 0;
    expectedCycleEndTime = 0;
    cycleStartTime = 0;
    //        nextCycleStartTime          = 0;
    status = Status.initializing;
    cycleNumber = 0;

    awaitedEventList = Collections.synchronizedSet(new HashSet<Fireable>());
    awaitedSimEventList = Collections.synchronizedSet(new HashSet<Fireable>());
    firedEventList = new HashSet<Fireable>();

    readyToShutdown = false;
    emergencyStopRequested = false;
    emergencyStopActive = false;
    emergencyStopIsToBeThrown = false;
    emergencyStopCausedBy = null;

    synchronizedTasks = Collections.synchronizedList(new ArrayList<Runnable>());
    cyclicTasks = Collections.synchronizedList(new ArrayList<CyclicTask>());

    startCycle = new Semaphore(1);
    cycleEnded = new Semaphore(1);

    startCycling = new Synchronisation();
    stopCycling = new Synchronisation();
    shutdownRequest = new Synchronisation();

    running = false;

    activeEventsLock = new CountingLock();
    awaitedEventOfLastModule = null;

    moduleList = new ArrayList<AbstractModule>(20);
    traceQueue = null;

    cycleHistogramm = null;
    systemHistogramm = null;
    modulesHistogramm = null;
    processedModule = null;

    exitCode = 0;

    incrementCounter = 0;
    decrementCounter = 0;

    try {
        propCycleTime = new LongProperty(this, "CycleTime", DEFAULTCYCLETIME, "[ns]", true);
        propCycleTimeoutTime = new LongProperty(this, "CycleTimeoutTime", DEFAULTCYCLETIMEOUTTIME, "[ns]",
                true);
        propCycleMode = new StringProperty(this, "CycleMode", CycleMode.FreeRunning.toString(),
                "[OneCycle | Bound | LazyBound | FreeRunning]", true);
        propRunningInsideAnIde = new BooleanProperty(this, "RunningInsideAnIde", false,
                "will pop up a small window to close the application", true);
        propRunningInjUnitTest = new BooleanProperty(this, "RunningInjUnitTest", false,
                "helpful, if jPac is run in a jUnit test", true);
        propEnableTrace = new BooleanProperty(this, "EnableTrace", false,
                "enables tracing of the module activity", true);
        propTraceTimeMinutes = new IntProperty(this, "TraceTimeMinutes", 0,
                "used to estimate the length of the trace buffer [min]", true);
        propPauseOnBreakPoint = new BooleanProperty(this, "pauseOnBreakPoint", false,
                "cycle is paused, until all modules enter waiting state", true);
        propRemoteSignalsEnabled = new BooleanProperty(this, "RemoteSignalsEnabled", false,
                "enable connections to/from remote JPac instances", true);
        propRemoteSignalPort = new IntProperty(this, "RemoteSignalPort", 10002,
                "server port for remote signal access", true);
        propStoreHistogrammsOnShutdown = new BooleanProperty(this, "storeHistogrammsOnShutdown", false,
                "enables storing of histogramm data on shutdown", true);
        propHistogrammFile = new StringProperty(this, "HistogrammFile", "./data/histogramm.csv",
                "file in which the histogramms are stored", true);
        propCyclicTaskShutdownTimeoutTime = new LongProperty(this, "CyclicTaskShutdownTimeoutTime",
                DEFAULTCYCLICTASKSHUTDOWNTIMEOUTTIME, "Timeout for all cyclic tasks to stop on shutdown [ns]",
                true);
        instanceIdentifier = InetAddress.getLocalHost().getHostName() + ":" + propRemoteSignalPort.get();
        cycleTime = propCycleTime.get();
        cycleTimeoutTime = propCycleTimeoutTime.get();
        cycleMode = CycleMode.valueOf(propCycleMode.get());
        runningInsideAnIde = propRunningInsideAnIde.get();
        runningInjUnitTest = propRunningInjUnitTest.get();
        enableTrace = propEnableTrace.get();
        traceTimeMinutes = propTraceTimeMinutes.get();
        pauseOnBreakPoint = propPauseOnBreakPoint.get();
        remoteSignalsEnabled = propRemoteSignalsEnabled.get();
        remoteSignalPort = propRemoteSignalPort.get();
        storeHistogrammsOnShutdown = propStoreHistogrammsOnShutdown.get();
        histogrammFile = propHistogrammFile.get();
        cyclicTaskShutdownTimeoutTime = propCyclicTaskShutdownTimeoutTime.get();
        //install configuration saver
        try {
            registerCyclicTask(Configuration.getInstance().getConfigurationSaver());
        } catch (WrongUseException exc) {
            /*cannot happen*/}
    } catch (UnknownHostException ex) {
        Log.error("Error: ", ex);
        //properties cannot be initialized
        //kill application
        System.exit(99);
    } catch (ConfigurationException ex) {
        Log.error("Error: ", ex);
        //properties cannot be initialized
        //kill application
        System.exit(99);
    }

    //install a shutdown hook to handle application shutdowns
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());
    setPriority(MAX_PRIORITY);
    //start instance of the automationController
    start();
}

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

@Test
public void testRespectsBufferMax() throws InterruptedException {
    final AtomicInteger droppedEvents = new AtomicInteger(0);
    final Semaphore semaphoreA = new Semaphore(0);
    final Semaphore semaphoreB = new Semaphore(0);
    final Semaphore semaphoreC = new Semaphore(-2);
    final AtomicInteger recordsReceived = new AtomicInteger(0);

    _wireMockRule.stubFor(WireMock.requestMatching(new RequestValueMatcher(r -> {
        recordsReceived.incrementAndGet();

        // Annotations
        Assert.assertEquals(0, r.getAnnotationsCount());

        // Dimensions
        Assert.assertEquals(0, r.getDimensionsCount());

        // Samples
        assertSample(r.getTimersList(), "timer", 7d);
        assertSample(r.getCountersList(), "counter", 8d);
        assertSample(r.getGaugesList(), "gauge", 9d);
    })).willReturn(WireMock.aResponse().withStatus(200)));

    final Sink sink = new ApacheHttpSink.Builder()
            .setUri(URI.create("http://localhost:" + _wireMockRule.port() + PATH)).setMaxBatchSize(2)
            .setParallelism(1).setBufferSize(5).setEmptyQueueInterval(Duration.ofMillis(1000))
            .setEventHandler(//w ww . j  ava2s .  c  o m
                    new RespectsMaxBufferEventHandler(semaphoreA, semaphoreB, semaphoreC, droppedEvents))
            .build();

    final TsdEvent event = new TsdEvent(Collections.emptyMap(),
            createQuantityMap("timer", TsdQuantity.newInstance(7d, null)),
            createQuantityMap("counter", TsdQuantity.newInstance(8d, null)),
            createQuantityMap("gauge", TsdQuantity.newInstance(9d, null)));

    // Add one event to be used as a synchronization point
    sink.record(event);
    semaphoreA.acquire();

    // Add the actual events to analyze
    for (int x = 0; x < 10; x++) {
        sink.record(event);
    }
    semaphoreB.release();
    semaphoreC.acquire();

    // Ensure expected handler was invoked
    Assert.assertEquals(5, droppedEvents.get());

    // Assert number of records received
    Assert.assertEquals(6, recordsReceived.get());

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

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

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

@Test
public void shouldReturnBackupRunningSinceValue_inISO8601_format() throws InterruptedException {
    assertThat(backupService.backupRunningSinceISO8601(), is(Optional.empty()));

    final Semaphore waitForBackupToStart = new Semaphore(1);
    final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1);
    final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() {
        private boolean backupStarted = false;

        @Override//  ww w.  java2  s  .c  o m
        public void updateStep(BackupProgressStatus step) {
            if (!backupStarted) {
                backupStarted = true;
                waitForBackupToStart.release();
                try {
                    waitForAssertionToCompleteWhileBackupIsOn.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        @Override
        public void error(String message) {
        }

        @Override
        public void completed() {
        }
    };

    waitForAssertionToCompleteWhileBackupIsOn.acquire();
    waitForBackupToStart.acquire();
    Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener));

    backupThd.start();
    waitForBackupToStart.acquire();
    String backupStartedTimeString = backupService.backupRunningSinceISO8601().get();
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
    DateTime backupTime = dateTimeFormatter.parseDateTime(backupStartedTimeString);

    ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup");
    assertThat(new DateTime(runningBackup.getTime()), is(backupTime));
    waitForAssertionToCompleteWhileBackupIsOn.release();
    backupThd.join();
}