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.qeo.deviceregistration.helper.RegistrationCredentialsWriterTask.java

/**
 * Create instance.//from w  w  w . j a va  2s .c  o  m
 *
 * @param ctx     activity context.
 * @param device  unregistered device detail to register.
 * @param realmId The realmId of the realm where to add the user/device to
 * @param userId  The userId of the user where to add the device to.
 */
public RegistrationCredentialsWriterTask(Context ctx, UnRegisteredDeviceModel device, long realmId,
        long userId) {
    if (userId <= 0) {
        throw new IllegalArgumentException("Invalid userId");
    }
    mSem = new Semaphore(0);
    mDeviceObject = device;
    this.mDeviceName = device.getUserFriendlyName();
    mCtx = ctx;
    mRealmId = realmId;
    mUserId = userId;
    mBroadcastManager = LocalBroadcastManager.getInstance(mCtx);
    mIntent = new Intent(ACTION_REGISTRATION_QEO_DONE);
}

From source file:org.apache.asterix.experiment.client.StatisticsQueryGenerator.java

public void start() throws Exception {
    final Semaphore sem = new Semaphore(0);
    threadPool.submit(new QueryGenerator(sem, config));
    sem.acquire();/*from  w  w  w .  jav  a2s . c o  m*/
}

From source file:com.bt.aloha.batchtest.ultramonkey.SyncServiceImpl.java

@Override
public void terminateCall(String callId) {
    synchronized (terminateCallLock) {
        super.terminateCall(callId);
        callTerminatedSemaphores.put(callId, new Semaphore(0));
    }//from  ww w .j  a v a 2  s . c  o m
    if (waitForCallTerminatedEvent(callId)) {
        return;
    }
    throw new ServiceException("No call terminated event received for callId " + callId);
}

From source file:org.apache.synapse.debug.SynapseDebugInterface.java

/**
 * Initializes the communication command and event channels asynchronously.
 *
 * @param listenPortParam command port number
 * @param sendPortParam   event port number
 *///from  ww  w.j a v a  2  s .c o m
public void init(final int listenPortParam, final int sendPortParam) throws InterruptedException, IOException {
    log.info(SynapseDebugInterfaceConstants.LISTEN_ON_PORTS + " : Command " + listenPortParam + " - Event "
            + sendPortParam);
    this.runtimeSuspensionSem = new Semaphore(0);
    Thread channelCreator = new Thread(
            new AsynchronousChannelCreator(listenPortParam, sendPortParam, runtimeSuspensionSem));
    channelCreator.start();
    this.runtimeSuspensionSem.acquire();
    if (uncaughtException != null) {
        throw (IOException) uncaughtException;
    }
}

From source file:org.apache.hadoop.mapred.gridmix.JobSubmitter.java

/**
 * Initialize the submission component with downstream monitor and pool of
 * files from which split data may be read.
 * @param monitor Monitor component to which jobs should be passed
 * @param threads Number of submission threads
 *   See {@link Gridmix#GRIDMIX_SUB_THR}.
 * @param queueDepth Max depth of pending work queue
 *   See {@link Gridmix#GRIDMIX_QUE_DEP}.
 * @param inputDir Set of files from which split data may be mined for
 * synthetic job// w  w w .j  a  v a 2  s .  c  o  m
 * @param statistics
 */
public JobSubmitter(JobMonitor monitor, int threads, int queueDepth, FilePool inputDir, Statistics statistics) {
    sem = new Semaphore(queueDepth);
    sched = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    this.inputDir = inputDir;
    this.monitor = monitor;
    this.statistics = statistics;
}

From source file:org.artifactory.storage.db.binstore.service.FileCacheBinaryProviderImpl.java

public FileCacheBinaryProviderImpl(File rootDataDir, StorageProperties storageProperties) {
    super(getDataFolder(rootDataDir, storageProperties, StorageProperties.Key.binaryProviderCacheDir, "cache"));
    lruCache = Maps.newConcurrentMap();//  ww w . ja  v a2 s  . c o m
    totalSize = new AtomicLong(0);
    maxTotalSize = storageProperties.getBinaryProviderCacheMaxSize();
    cacheCleanerSemaphore = new Semaphore(1);
}

From source file:org.apache.ranger.common.TestTimedExecutor.java

@Test
public void test() throws InterruptedException {
    /*// www.  j av  a  2 s .  c  om
     * Create a pool with 2 threads and queue size of 3 such that 6th item should get rejected right away due to capacity.
     */
    int poolSize = 2;
    int queueSize = 3;
    _configurator = new TimedExecutorConfigurator(poolSize, queueSize);
    // Just toa void thread shutting down and restarting set keep alive to high value.
    _executor.initialize(_configurator);

    // now create 2 callalbles that would keep waiting unless we ask them to proceed
    // create an executor which would simulate simultaneous threads calling into executor to perform lookups
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<Future<Integer>> futures = new ArrayList<Future<Integer>>();
    /*
     * We would have 2 permits for 10 callables, such that
     * - 2 should succeed
     * - 5 should timeout (2 in pool + 3 in queue)
     * - 3 should get rejected.
     */
    Semaphore semaphore = new Semaphore(2);
    /*
     * We need a latch to keep track of when the processing is done so we can check the results of teh test
     */
    CountDownLatch latch = new CountDownLatch(10);
    // Callables will record exception in this map
    final ConcurrentMap<String, AtomicInteger> results = new ConcurrentHashMap<String, AtomicInteger>();
    for (int i = 0; i < 10; i++) {
        LookupTask lookupTask = new LookupTask(i, semaphore);
        TimedTask timedTask = new TimedTask(_executor, lookupTask, 1, TimeUnit.SECONDS, results, latch);
        Future<Integer> aFuture = executorService.submit(timedTask);
        futures.add(aFuture);
    }
    // Let's wait for the threads to finish
    LOG.debug("Starting to wait for threadpool to finish");
    latch.await();
    /*
     * depending on how threads get scheduled the count in results would vary, except we know for sure that.
     * - 2 must succeed since we have exactly 2 permits available.
     * - sum of timed out and rejected must be equal to 8.
       * - at least 3 and no more than 5 tasks must get rejected.
       * - at least 3 and no more than 5 tasks must get timed out
     */
    int successCount = results.get("success").get();
    int timeoutCount = results.get("java.util.concurrent.TimeoutException").get();
    int rejectedCount = results.get("java.util.concurrent.RejectedExecutionException").get();
    assertEquals("success count", 2, successCount);
    assertTrue("timeout[" + timeoutCount + "]: 3 <= count(timeout) <= 5",
            timeoutCount >= 3 && timeoutCount <= 5);
    assertTrue("rejected[" + rejectedCount + "]: 3 <= count(timeout) <= 5",
            rejectedCount >= 3 && rejectedCount <= 5);
    assertEquals("total should equal 10", 10, successCount + timeoutCount + rejectedCount);
    _executor.shutdown();
}

From source file:org.apache.kylin.storage.hbase.util.HbaseStreamingInput.java

public static void addData(String tableName) throws IOException {

    createTable(tableName);//from w  w w  .  j  a v a  2s. c om

    final Semaphore semaphore = new Semaphore(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            scheduleJob(semaphore, 300000);//5 minutes a batch
        }
    }).start();

    while (true) {
        try {
            semaphore.acquire();
            int waiting = semaphore.availablePermits();
            if (waiting > 0) {
                logger.warn("There are another " + waiting + " batches waiting to be added");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }

        Connection conn = getConnection();
        Table table = conn.getTable(TableName.valueOf(tableName));

        byte[] key = new byte[8 + 4];//time + id

        logger.info("============================================");
        long startTime = System.currentTimeMillis();
        logger.info("data load start time in millis: " + startTime);
        logger.info("data load start at " + formatTime(startTime));
        List<Put> buffer = Lists.newArrayList();
        for (int i = 0; i < (1 << 10); ++i) {
            long time = System.currentTimeMillis();
            Bytes.putLong(key, 0, time);
            Bytes.putInt(key, 8, i);
            Put put = new Put(key);
            byte[] cell = randomBytes(CELL_SIZE);
            put.addColumn(CF, QN, cell);
            buffer.add(put);
        }
        table.put(buffer);
        table.close();
        conn.close();
        long endTime = System.currentTimeMillis();
        logger.info("data load end at " + formatTime(endTime));
        logger.info("data load time consumed: " + (endTime - startTime));
        logger.info("============================================");
    }
}

From source file:org.openhab.io.mqttembeddedbroker.internal.MqttEmbeddedBrokerServiceTest.java

public void waitForConnectionChange(MqttBrokerConnection c, MqttConnectionState expectedState)
        throws InterruptedException {
    Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();/*from   ww  w. j  a va 2 s .c o m*/

    MqttConnectionObserver mqttConnectionObserver = (state, error) -> {
        if (state == expectedState) {
            semaphore.release();
        }
    };
    c.addConnectionObserver(mqttConnectionObserver);
    if (c.connectionState() == expectedState) {
        semaphore.release();
    }

    // Start the connection and wait until timeout or connected callback returns.
    semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);

    c.removeConnectionObserver(mqttConnectionObserver);

}

From source file:io.mindmaps.engine.loader.DistributedLoader.java

public DistributedLoader(String graphNameInit, Collection<String> hosts) {
    ConfigProperties prop = ConfigProperties.getInstance();
    batchSize = prop.getPropertyAsInt(ConfigProperties.BATCH_SIZE_PROPERTY);
    graphName = graphNameInit;//from w ww.  j  a va 2s. c  om
    batch = new HashSet<>();
    hostsArray = hosts.toArray(new String[hosts.size()]);
    currentHost = 0;
    pollingFrequency = 30000;

    threadsNumber = prop.getAvailableThreads() * 3;

    // create availability map
    availability = new HashMap<>();
    hosts.forEach(h -> availability.put(h, new Semaphore(threadsNumber)));

    jobsTerminated = new HashMap<>();
    hosts.forEach(h -> jobsTerminated.put(h, 0));
}