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.telegram.ui.ChannelEditActivity.java

@SuppressWarnings("unchecked")
@Override//from  w w w .j av  a2 s . co  m
public boolean onFragmentCreate() {
    currentChat = MessagesController.getInstance().getChat(chatId);
    if (currentChat == null) {
        final Semaphore semaphore = new Semaphore(0);
        MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
            @Override
            public void run() {
                currentChat = MessagesStorage.getInstance().getChat(chatId);
                semaphore.release();
            }
        });
        try {
            semaphore.acquire();
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
        if (currentChat != null) {
            MessagesController.getInstance().putChat(currentChat, true);
        } else {
            return false;
        }
        if (info == null) {
            MessagesStorage.getInstance().loadChatInfo(chatId, semaphore, false, false);
            try {
                semaphore.acquire();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            if (info == null) {
                return false;
            }
        }
    }
    avatarUpdater.parentFragment = this;
    avatarUpdater.delegate = this;
    signMessages = currentChat.signatures;
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
    return super.onFragmentCreate();
}

From source file:org.apache.synapse.transport.fix.FIXIncomingMessageHandler.java

public FIXIncomingMessageHandler(ConfigurationContext cfgCtx, WorkerPool workerPool, AxisService service,
        boolean acceptor) {
    this.cfgCtx = cfgCtx;
    this.workerPool = workerPool;
    this.service = service;
    this.log = LogFactory.getLog(this.getClass());
    this.acceptor = acceptor;
    countersMap = new ConcurrentHashMap<SessionID, AtomicInteger>();
    outgoingMessages = new LinkedBlockingQueue<MessageContext>();
    semaphore = new Semaphore(0);
    getResponseHandlingApproach();//from  w ww.j  ava 2  s  .co  m

    Parameter eventHandlerParam;
    if (acceptor) {
        eventHandlerParam = service.getParameter(FIXConstants.FIX_ACCEPTOR_EVENT_HANDLER);
    } else {
        eventHandlerParam = service.getParameter(FIXConstants.FIX_INITIATOR_EVENT_HANDLER);
    }

    if (eventHandlerParam != null && eventHandlerParam.getValue() != null
            && !"".equals(eventHandlerParam.getValue())) {
        try {
            Class clazz = getClass().getClassLoader().loadClass((String) eventHandlerParam.getValue());
            eventHandler = (SessionEventHandler) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            log.error("Unable to find the session event handler class: " + eventHandlerParam.getValue(), e);
        } catch (Exception e) {
            log.error(
                    "Error while initializing the session event handler class: " + eventHandlerParam.getValue(),
                    e);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorCluster.java

@Test
public void testLostRestart() throws Exception {
    final Timing timing = new Timing();

    CuratorFramework client = null;//from www.  j  a v a 2s . co  m
    TestingCluster cluster = new TestingCluster(3);
    cluster.start();
    try {
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();
        client.sync("/", null);

        final AtomicReference<Exception> error = new AtomicReference<Exception>(null);
        final AtomicReference<String> lockNode = new AtomicReference<String>(null);
        final Semaphore semaphore = new Semaphore(0);
        final CountDownLatch lostLatch = new CountDownLatch(1);
        final CountDownLatch internalLostLatch = new CountDownLatch(1);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                try {
                    List<String> names = client.getChildren().forPath("/leader");
                    if (names.size() != 1) {
                        semaphore.release();
                        Exception exception = new Exception("Names size isn't 1: " + names.size());
                        error.set(exception);
                        return;
                    }
                    lockNode.set(names.get(0));

                    semaphore.release();
                    if (!timing.multiple(4).awaitLatch(internalLostLatch)) {
                        error.set(new Exception("internalLostLatch await failed"));
                    }
                } finally {
                    lostLatch.countDown();
                }
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    internalLostLatch.countDown();
                }
            }
        };
        LeaderSelector selector = new LeaderSelector(client, "/leader", listener);
        selector.start();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
        if (error.get() != null) {
            throw new AssertionError(error.get());
        }

        Collection<InstanceSpec> instances = cluster.getInstances();
        cluster.stop();

        Assert.assertTrue(timing.multiple(4).awaitLatch(lostLatch));
        timing.sleepABit();
        Assert.assertFalse(selector.hasLeadership());

        Assert.assertNotNull(lockNode.get());

        cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()]));
        cluster.start();

        try {
            client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration
        } catch (Exception ignore) {
            // ignore
        }

        Assert.assertTrue(semaphore.availablePermits() == 0);
        Assert.assertFalse(selector.hasLeadership());

        selector.requeue();
        Assert.assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
    } finally {
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

From source file:org.wso2.carbon.databridge.agent.thrift.Agent.java

public Agent(AgentConfiguration agentConfiguration) {
    this.agentConfiguration = agentConfiguration;
    this.transportPool = new ClientPool().getClientPool(new ClientPoolFactory(),
            agentConfiguration.getMaxTransportPoolSize(), agentConfiguration.getMaxIdleConnections(), true,
            agentConfiguration.getEvictionTimePeriod(), agentConfiguration.getMinIdleTimeInPool());
    this.secureTransportPool = new SecureClientPool().getClientPool(
            new SecureClientPoolFactory(agentConfiguration.getTrustStore(),
                    agentConfiguration.getTrustStorePassword()),
            agentConfiguration.getSecureMaxTransportPoolSize(),
            agentConfiguration.getSecureMaxIdleConnections(), true,
            agentConfiguration.getSecureEvictionTimePeriod(), agentConfiguration.getSecureMinIdleTimeInPool());
    this.agentAuthenticator = AgentAuthenticatorFactory.getAgentAuthenticator(secureTransportPool);
    this.dataPublisherList = new LinkedList<DataPublisher>();
    this.queueSemaphore = new Semaphore(agentConfiguration.getBufferedEventsSize());
    //for the unbounded queue implementation the maximum pool size irrelevant and
    // only the CorePoolSize number of threads will be created
    this.threadPool = new ThreadPoolExecutor(agentConfiguration.getPoolSize(),
            agentConfiguration.getMaxPoolSize(), AgentConstants.DEFAULT_KEEP_ALIVE_TIME, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new DataBridgeThreadFactory("Agent"));
}

From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java

@Test
public void testWithNamespaceAndLostSession() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
            .retryPolicy(new ExponentialBackoffRetry(100, 3)).namespace("aisa").build();
    try {//from   ww  w .  j  a va  2  s  . c  om
        client.start();

        client.create().forPath("/test-me");

        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        server.stop();

        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            client.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
            // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));

        timing.sleepABit();

        server = new TestingServer(server.getPort(), server.getTempDirectory());
        Assert.assertTrue(timing.awaitLatch(latch));

        timing.sleepABit();

        Assert.assertNull(client.checkExists().forPath("/test-me"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

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

@Test
public void testCancelSingleTask() throws Exception {
    Semaphore idleWorkersSemaphore = new Semaphore(0);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() {
    });//  w  w w.  j  a v a  2s.co m
    Task task = getSleepIncrementTask();
    workerPool.assignTask(task);
    Thread.sleep(10);
    workerPool.abortTask(task.clusterName);
    Thread.sleep(100);
    Assert.assertEquals(1, idleWorkersSemaphore.availablePermits());
}

From source file:org.oxymores.chronix.engine.ChronixEngine.java

public ChronixEngine(String dbPath, String mainInterface, String transacUnitName, String historyUnitName,
        boolean runnerMode, int nbRunner, String historyDBPath, String transacDbPath) {
    this.dbPath = dbPath;
    this.runnerMode = runnerMode;
    this.transacUnitName = transacUnitName;
    this.historyUnitName = historyUnitName;
    this.brokerInterface = mainInterface;
    this.brokerInterfaceNoPort = this.brokerInterface.split(":")[0];
    this.brokerPort = Integer.parseInt(this.brokerInterface.split(":")[1]);
    this.nbRunner = nbRunner;
    this.historyDbPath = historyDBPath;
    this.transacDbPath = transacDbPath;

    // To allow some basic configuration before starting nodes, we init the minimal fields inside the context
    this.ctx = ChronixContext.initContext(dbPath, transacUnitName, historyUnitName, mainInterface, false);

    // Startup phase is synchronized with this
    this.startCritical = new Semaphore(1);
    // Putting a token in this will stop the engine
    this.stop = new Semaphore(0);
    this.threadInit = new Semaphore(0);
    // A token is created when the engines stops. (not when it reboots)
    this.stopped = new Semaphore(0);
    // The stop & start sequence is protected with this
    this.stopping = new Semaphore(1);
}

From source file:org.commoncrawl.mapred.ec2.parser.EC2ParserTask.java

public EC2ParserTask(Configuration conf) throws Exception {

    super(conf);/*from w w  w .  ja v  a 2s  . c om*/

    if (!conf.getBoolean(CONF_PARAM_TEST_MODE, false)) {
        conf.set(VALID_SEGMENTS_PATH_PROPERTY, VALID_SEGMENTS_PATH);
        conf.set(SEGMENT_PATH_PROPERTY, SEGMENTS_PATH);
        conf.set(JOB_LOGS_PATH_PROPERTY, JOB_LOGS_PATH);
        conf.set(CHECKPOIINTS_PATH_PROPERTY, CHECKPOINTS_PATH);

        jobThreadSemaphore = new Semaphore(-(MAX_SIMULTANEOUS_JOBS - 1));

    } else {
        conf.set(VALID_SEGMENTS_PATH_PROPERTY, TEST_VALID_SEGMENTS_PATH);
        conf.set(SEGMENT_PATH_PROPERTY, TEST_SEGMENTS_PATH);
        conf.set(JOB_LOGS_PATH_PROPERTY, TEST_JOB_LOGS_PATH);

        jobThreadSemaphore = new Semaphore(0);
        maxSimultaneousJobs = 1;
    }

    FileSystem fs = FileSystem.get(new URI("s3n://aws-publicdatasets"), conf);
    LOG.info(
            "FileSystem is:" + fs.getUri() + " Scanning for candidates at path:" + CRAWL_LOG_INTERMEDIATE_PATH);
    TreeSet<Path> candidateSet = buildCandidateList(fs, new Path(CRAWL_LOG_INTERMEDIATE_PATH));
    LOG.info("Scanning for completed segments");
    List<Path> processedLogs = scanForCompletedSegments(fs, conf);
    LOG.info("Found " + processedLogs.size() + " processed logs");
    // remove processed from candidate set ... 
    candidateSet.removeAll(processedLogs);
    // ok we are ready to go .. 
    LOG.info("There are: " + candidateSet.size() + " logs in need of parsing");
    while (candidateSet.size() != 0) {
        ImmutableList.Builder<Path> pathBuilder = new ImmutableList.Builder<Path>();
        Iterator<Path> iterator = Iterators.limit(candidateSet.iterator(), LOGS_PER_ITERATION);
        while (iterator.hasNext()) {
            pathBuilder.add(iterator.next());
            iterator.remove();
        }
        LOG.info("Queueing Parse");
        queue(fs, conf, pathBuilder.build());
        LOG.info("Queued Parse");

        // in test mode, queue only a single segment's worth of data 
        if (conf.getBoolean(CONF_PARAM_TEST_MODE, false)) {
            LOG.info("Test Mode - Queueing only a single Item");
            break;
        }
    }

    // queue shutdown items 
    for (int i = 0; i < maxSimultaneousJobs; ++i) {
        _queue.put(new QueueItem());
    }
}

From source file:com.yahoo.omid.benchmarks.tso.TxRunner.java

public TxRunner(MetricsRegistry metrics, Config expConfig)
        throws IOException, InterruptedException, ExecutionException {

    // Tx Runner config
    this.outstandingTxs = new Semaphore(expConfig.maxInFlight);
    this.maxTxSize = expConfig.maxTxSize;
    this.commitDelay = expConfig.commitDelay;
    this.percentReads = expConfig.readproportion == -1 ? expConfig.percentReads
            : (expConfig.readproportion * 100);
    this.intGenerator = GeneratorUtils.getIntGenerator(expConfig.requestDistribution);
    this.randomGen = new Random(System.currentTimeMillis() * txRunnerId); // to make it channel dependent

    LOG.info("TxRunner-{} [ Row Distribution -> {} ]", txRunnerId, expConfig.requestDistribution);
    LOG.info("TxRunner-{} [ Outstanding transactions -> {} ]", txRunnerId, expConfig.maxInFlight);
    LOG.info("TxRunner-{} [ Max Tx Size -> {} ]", txRunnerId, expConfig.maxTxSize);
    LOG.info("TxRunner-{} [ Commit delay -> {}:{} ]", txRunnerId, expConfig.commitDelay.timeValue,
            expConfig.commitDelay.timeUnit);
    LOG.info("TxRunner-{} [ % reads -> {} ]", txRunnerId, expConfig.percentReads);

    // Commit table client initialization
    CommitTable commitTable;//from w  w w .ja  va 2 s.  c o m
    if (expConfig.isHBase()) {
        HBaseLogin.loginIfNeeded(expConfig.getLoginFlags());
        HBaseCommitTableConfig hbaseCommitTableConfig = new HBaseCommitTableConfig();
        hbaseCommitTableConfig.setTableName(expConfig.getHBaseCommitTable());
        commitTable = new HBaseCommitTable(HBaseConfiguration.create(), hbaseCommitTableConfig);
        LOG.info("TxRunner-{} [ Using HBase Commit Table ]", txRunnerId);
    } else {
        commitTable = new NullCommitTable();
        LOG.info("TxRunner-{} [ Using Null Commit Table ]", txRunnerId);
    }
    try {
        this.commitTableClient = commitTable.getClient().get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        e.printStackTrace();
        throw e;
    } catch (ExecutionException e) {
        e.printStackTrace();
        throw e;
    }

    // TSO Client initialization
    Configuration tsoConfig = new BaseConfiguration();
    tsoConfig.setProperty(TSO_HOST_CONFKEY, expConfig.tsoHostPort.getHostText());
    tsoConfig.setProperty(TSO_PORT_CONFKEY, expConfig.tsoHostPort.getPortOrDefault(1234));
    tsoConfig.setProperty("request.timeout-ms", -1); // TODO ???
    LOG.info("TxRunner-{} [ Connected to TSO in {} ]", txRunnerId, expConfig.tsoHostPort);

    this.tsoClient = TSOClient.newBuilder().withConfiguration(tsoConfig).build();

    // Stat initialization
    String hostName = InetAddress.getLocalHost().getHostName();
    this.timestampTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "timestamp"));
    this.commitTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "commit"));
    this.abortTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "abort"));
    this.errorCounter = metrics.counter(name("tx_runner", Integer.toString(txRunnerId), hostName, "errors"));

}