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:org.wso2.carbon.databridge.agent.endpoint.DataEndpoint.java

public void initialize(DataEndpointConfiguration dataEndpointConfiguration)
        throws DataEndpointException, DataEndpointAuthenticationException, TransportException {
    this.transportPool = dataEndpointConfiguration.getTransportPool();
    this.batchSize = dataEndpointConfiguration.getBatchSize();
    this.connectionWorker = new DataEndpointConnectionWorker();
    this.connectionWorker.initialize(this, dataEndpointConfiguration);
    this.threadPoolExecutor = new EventPublisherThreadPoolExecutor(dataEndpointConfiguration.getCorePoolSize(),
            dataEndpointConfiguration.getMaxPoolSize(), dataEndpointConfiguration.getKeepAliveTimeInPool(),
            dataEndpointConfiguration.getReceiverURL());
    this.connectionService = Executors.newSingleThreadExecutor(
            new DataBridgeThreadFactory("ConnectionService-" + dataEndpointConfiguration.getReceiverURL()));
    this.maxPoolSize = dataEndpointConfiguration.getMaxPoolSize();
    this.immediateDispatchSemaphore = new Semaphore(maxPoolSize);
    connect();//from  ww w  .  j av a  2s. co m
}

From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testChainedTask() throws Exception {
    TaskBase task = new SleepIncrementTask(100).andThen(new SleepIncrementTask(150))
            .andThen(new SleepIncrementTask(200)).getEntity();

    final CountDownLatch latch = new CountDownLatch(3);
    FIFOTaskQueue tq = new FIFOTaskQueue(10) {
        @Override// www  .j  a  v  a2 s.  c o m
        public boolean finishTask(final long id, final String output) {
            latch.countDown();
            return super.finishTask(id, output);
        }

        @Override
        public long finishTaskAndEnqueueRunningTask(final long id, final String output, final TaskBase newTask,
                final String worker) {
            latch.countDown();
            return super.finishTaskAndEnqueueRunningTask(id, output, newTask, worker);
        }
    };
    tq.enqueueTask(task, Integer.toString(++nameCounter), 0);

    Semaphore idleWorkersSemaphore = new Semaphore(2);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, tq);
    TaskDispatcher dispatcher = new TaskDispatcher(2, idleWorkersSemaphore, workerPool, tq);
    dispatcher.start();

    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(SleepIncrementTask.executionCounter.intValue(), 3);

    Assert.assertEquals(tq.getResult(0), "0");
    Assert.assertEquals(tq.getResult(1), "1");
    Assert.assertEquals(tq.getResult(2), "2");
    dispatcher.stop();
}

From source file:it.unibo.alchemist.boundary.monitors.RecordingMonitor.java

/**
 * RecordingMonitor<T> empty constructor.
 *//*from  ww  w .j  a v a2s  .  c o  m*/
public RecordingMonitor() {
    super();
    setFilePath(defaultFilePath);
    mutex = new Semaphore(1);
}

From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java

@Override
public long start(String jobName, Properties params) throws JobStartException, JobSecurityException {
    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params);
    batchContext.setValidating(false);/*from www.j av a  2s .  c  o  m*/

    Resource batchXml = new ClassPathResource("/META-INF/batch.xml");
    String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml";
    Resource jobXml = new ClassPathResource(jobConfigurationLocation);

    if (batchXml.exists()) {
        batchContext.load(batchXml);
    }

    if (jobXml.exists()) {
        batchContext.load(jobXml);
    }

    AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
            .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean")
            .getBeanDefinition();
    beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
    batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition);

    batchContext.setParent(parentContext);

    try {
        batchContext.refresh();
    } catch (BeanCreationException e) {
        throw new JobStartException(e);
    }

    Assert.notNull(jobName, "The job name must not be null.");

    final org.springframework.batch.core.JobExecution jobExecution;

    try {
        JobParameters jobParameters = jobParametersConverter.getJobParameters(params);
        String[] jobNames = batchContext.getBeanNamesForType(Job.class);

        if (jobNames == null || jobNames.length <= 0) {
            throw new BatchRuntimeException("No Job defined in current context");
        }

        org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0],
                jobParameters);
        jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation);
    } catch (Exception e) {
        throw new JobStartException(e);
    }

    try {
        final Semaphore semaphore = new Semaphore(1);
        final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>());
        semaphore.acquire();

        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                JsrJobContextFactoryBean factoryBean = null;
                try {
                    factoryBean = (JsrJobContextFactoryBean) batchContext
                            .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME);
                    factoryBean.setJobExecution(jobExecution);
                    final AbstractJob job = batchContext.getBean(AbstractJob.class);
                    addListenerToJobService.addListenerToJob(job);
                    semaphore.release();
                    // Initialization of the JobExecution for job level dependencies
                    jobRegistry.register(job, jobExecution);
                    job.execute(jobExecution);
                    jobRegistry.remove(jobExecution);
                } catch (Exception e) {
                    exceptionHolder.add(e);
                } finally {
                    if (factoryBean != null) {
                        factoryBean.close();
                    }

                    batchContext.close();

                    if (semaphore.availablePermits() == 0) {
                        semaphore.release();
                    }
                }
            }
        });

        semaphore.acquire();
        if (exceptionHolder.size() > 0) {
            semaphore.release();
            throw new JobStartException(exceptionHolder.get(0));
        }
    } catch (Exception e) {
        if (jobRegistry.exists(jobExecution.getId())) {
            jobRegistry.remove(jobExecution);
        }
        jobExecution.upgradeStatus(BatchStatus.FAILED);
        if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
            jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
        }
        jobRepository.update(jobExecution);

        if (batchContext.isActive()) {
            batchContext.close();
        }

        throw new JobStartException(e);
    }
    return jobExecution.getId();
}

From source file:org.chromium.android_webview.test.AwContentsTest.java

private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException {
    // Set up a container to hold the result object and a semaphore to
    // make the test wait for the result.
    final AtomicInteger val = new AtomicInteger();
    final Semaphore s = new Semaphore(0);
    final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) {
        @Override//from ww  w. j a  va 2s  .  com
        public void handleMessage(Message msg) {
            val.set(msg.arg1);
            s.release();
        }
    });
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            awContents.documentHasImages(msg);
        }
    });
    assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    int result = val.get();
    return result;
}

From source file:com.impetus.ankush.common.framework.ClusterPreValidator.java

public Map validate(final Map params) {
    final LinkedHashMap result = new LinkedHashMap();

    if (notContainsKey(params, "nodePorts", result)) {
        return result;
    }//from   ww  w  .j a v a 2  s  .co m
    if (params.containsKey(Constant.Keys.CLUSTERID)) {
        // Get cluster manager
        GenericManager<Cluster, Long> clusterManager = AppStoreWrapper.getManager(Constant.Manager.CLUSTER,
                Cluster.class);

        // get cluster id string
        String clusterIdStr = (String) params.get(Constant.Keys.CLUSTERID);
        // convert cluster id string into long value.
        Long clusterId = ParserUtil.getLongValue(clusterIdStr, 0);
        // Get the cluster object from database.
        Cluster cluster = clusterManager.get(clusterId);

        ClusterConfig clusterConfig = cluster.getClusterConfig();
        // set username
        params.put(Constant.Keys.USERNAME, clusterConfig.getAuthConf().getUsername());
        String pass = clusterConfig.getAuthConf().getPassword();
        if (pass != null && !pass.isEmpty()) {
            params.put(Constant.Keys.PASSWORD, pass);
        } else {
            params.put(Constant.Keys.PRIVATEKEY, clusterConfig.getAuthConf().getPrivateKey());
        }
        params.put(Constant.Agent.Key.AGENT_INSTALL_DIR, clusterConfig.getAgentInstallDir());
    } else {
        if (notContainsKey(params, Constant.Keys.USERNAME, result)) {
            return result;
        }
        if (notContainsKey(params, Constant.Keys.PASSWORD, result)) {
            return result;
        }
        if (notContainsKey(params, Constant.Keys.PRIVATEKEY, result)) {
            return result;
        }
    }
    final String username = (String) params.get(Constant.Keys.USERNAME);
    final String password = (String) params.get(Constant.Keys.PASSWORD);
    final String privateKey = (String) params.get(Constant.Keys.PRIVATEKEY);

    final Map nodePorts = (Map) params.get("nodePorts");
    Set<String> nodes = nodePorts.keySet();

    final boolean authUsingPassword = (password != null && !password.isEmpty());
    final String authInfo = authUsingPassword ? password : privateKey;

    try {
        final Semaphore semaphore = new Semaphore(nodes.size());
        for (final String hostname : nodes) {
            semaphore.acquire();

            AppStoreWrapper.getExecutor().execute(new Runnable() {

                @Override
                public void run() {
                    SSHExec conn = null;
                    LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
                    try {
                        conn = SSHUtils.connectToNode(hostname, username, password, privateKey);
                        map = getValidationMap(params, username, password, nodePorts, authUsingPassword,
                                authInfo, hostname, conn);
                    } catch (Exception e) {
                        map.put("error", new Status("Error", "Unable to perform validations", CRITICAL));
                        logger.error(e.getMessage(), e);

                    } finally {
                        // setting overall status.
                        map.put("status", getOverAllStatus((Collection) map.values()));
                        // putting map against node.
                        result.put(hostname, map);
                        if (semaphore != null) {
                            semaphore.release();
                        }
                        if (conn != null) {
                            conn.disconnect();
                        }
                    }
                }

            });
        }
        semaphore.acquire(nodes.size());
        result.put("status", true);
    } catch (Exception e) {
        String message = e.getMessage();
        if (message == null) {
            message = "Unable to validate nodes";
        }
        result.put("error", Collections.singletonList(message));
        result.put("status", false);
        logger.error(e.getMessage(), e);
    }
    return result;
}

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/*from w w  w.  j  av  a  2  s.  c o  m*/
        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:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@Test
public void testSimple() throws Exception {
    Timing timing = new Timing();
    DistributedQueue<String> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {//from   w w  w  .j  av a  2s.c om
        client.start();

        final List<String> messages = new CopyOnWriteArrayList<String>();
        final CountDownLatch latch = new CountDownLatch(2);
        final Semaphore semaphore = new Semaphore(0);
        QueueConsumer<String> consumer = new QueueConsumer<String>() {
            @Override
            public void consumeMessage(String message) throws Exception {
                messages.add(message);
                semaphore.acquire();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        queue = QueueBuilder.builder(client, consumer, serializer, "/queue")
                .executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue();
        queue.start();

        QueuePutListener<String> listener = new QueuePutListener<String>() {
            @Override
            public void putCompleted(String item) {
                latch.countDown();
            }

            @Override
            public void putMultiCompleted(MultiItem<String> items) {
            }
        };
        queue.getPutListenerContainer().addListener(listener);

        Assert.assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer
        Assert.assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue
        Assert.assertTrue(timing.awaitLatch(latch));
        timing.sleepABit();
        Assert.assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS));

        semaphore.release(100);
        Assert.assertTrue(queue.put("3", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS));
        Assert.assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS));

        for (int i = 0; i < 5; ++i) {
            if (messages.size() == 3) {
                break;
            }
            timing.sleepABit();
        }
        timing.sleepABit();

        Assert.assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5"));
    } finally {
        IOUtils.closeQuietly(queue);
        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//w  w  w .  jav  a  2s.  c  om
        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.hp.alm.ali.Handler.java

public void clear() {
    async = new Semaphore(100);
    firstError = null;
    requests.clear();
    cleanup.clear();
}