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:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testChainedTaskWithError() throws Exception {
    TaskBase task = new SleepIncrementTask(100).andThen(new ThrowingTask("Oops..."))
            .andThen(new SleepIncrementTask(150)).getEntity();

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

        @Override
        public boolean failTask(final long id, final String reason) {
            latch.countDown();
            return super.failTask(id, reason);
        }

        @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(), 1);

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

From source file:com.castlemock.web.basis.model.RepositoryImpl.java

/**
 * The method is responsible for retrieving a new write lock.
 * A new write lock will be created if a write lock already doesn't exist and is associated
 * with the provided <code>id</code>.
 * @param id The id is used as an identifier for the write lock
 * @return Either a new write lock or an already existing write lock associated with the <code>id</code>.
 * @since 1.5//from   w w  w  .j  av  a  2s. co m
 */
private synchronized Semaphore getWriteLock(final I id) {
    Semaphore writeLock = writeLocks.get(id);
    if (writeLock == null) {
        // Create a new write lock and only one is allowed to write to the file at a time.
        writeLock = new Semaphore(1);
        writeLocks.put(id, writeLock);
    }
    return writeLock;
}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testCache() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//w  w  w  . j a  v a  2s .  c  om
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class)
                .basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);
        cache.start();

        final Semaphore semaphore = new Semaphore(0);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                semaphore.release();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);

        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10065).build();
        discovery.registerService(instance1);
        Assert.assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS));

        discovery.registerService(instance2);
        Assert.assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS));

        ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("thing").name("another")
                .port(10064).build();
        discovery.registerService(instance3);
        Assert.assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.adobe.ags.curly.test.ErrorBehaviorTest.java

private void sync() {
    Semaphore test = new Semaphore(1);
    test.acquireUninterruptibly();/*  www  .j av a2 s . c om*/
    Platform.runLater(test::release);
    try {
        test.acquire();
    } catch (InterruptedException ex) {
        Logger.getLogger(ErrorBehaviorTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ikanow.infinit.e.api.knowledge.QueryHandler.java

private boolean acquireConcurrentAccessLock() throws InterruptedException {
    if (null == _concurrentAccessLock) {
        _concurrentAccessLock = new Semaphore(2);
    }/*from  w  w w  .j av a2s . c om*/
    return _concurrentAccessLock.tryAcquire(10, TimeUnit.MINUTES);
}

From source file:org.paxle.data.db.impl.CommandDBTest.java

@SuppressWarnings("unchecked")
private void storeUnknownLocation() throws InterruptedException {
    final int MAX = 10;

    // command-tracker must be called MAX times
    checking(new Expectations() {
        {//from www. j  a v a  2s.  c  o m
            exactly(MAX).of(cmdTracker).commandCreated(with(equal("org.paxle.data.db.ICommandDB")),
                    with(any(ICommand.class)));
        }
    });

    // generated test URI
    LinkedList<URI> knownURIs;
    LinkedList<URI> testURI = new LinkedList<URI>();
    for (int i = 0; i < MAX; i++) {
        testURI.add(URI.create("http://test.paxle.net/" + i));
    }
    knownURIs = (LinkedList<URI>) testURI.clone();

    // store them to DB
    int knownCount = this.cmdDB.storeUnknownLocations(0, 1, testURI);
    assertEquals(0, knownCount);

    // create a dummy data-sink
    Semaphore s = null;
    this.cmdDB.setDataSink(new DummyDataSink(s = new Semaphore(-MAX + 1)));

    // wait for all commands to be enqueued
    boolean acquired = s.tryAcquire(3, TimeUnit.SECONDS);
    assertTrue(acquired);

    // testing if all URI are known to the DB
    for (URI knownURI : knownURIs) {
        // command must be marked as crawled
        boolean known = this.cmdDB.isKnownInDB(knownURI, "CrawledCommand");
        assertTrue("Unkown URI: " + knownURI, known);

        // command must not be enqueued
        known = this.cmdDB.isKnownInDB(knownURI, "EnqueuedCommand");
        assertFalse("Unkown URI: " + knownURI, known);

        // command must be known to the cache
        known = this.cmdDB.isKnownInCache(knownURI);
        assertTrue(known);

        // command must be known to the bloom filter
        known = this.cmdDB.isKnownInDoubleURLs(knownURI);
        assertTrue(known);
    }
}

From source file:com.parse.ParseOkHttpClientTest.java

@Test
public void testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse() throws Exception {
    // Make mock response
    Buffer buffer = new Buffer();
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write("content".getBytes());
    gzipOut.close();/*  w  w  w. ja v  a 2 s .c  o  m*/
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + 201 + " " + "OK").setBody(buffer)
            .setHeader("Content-Encoding", "gzip");

    // Start mock server
    server.enqueue(mockResponse);
    server.start();

    ParseHttpClient client = new ParseOkHttpClient(10000, null);

    final Semaphore done = new Semaphore(0);
    // Add plain interceptor to disable decompress response stream
    client.addExternalInterceptor(new ParseNetworkInterceptor() {
        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();
            ParseHttpResponse parseResponse = chain.proceed(chain.getRequest());
            // Make sure the response we get from the interceptor is the raw gzip stream
            byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
            assertArrayEquals(byteOut.toByteArray(), content);

            // We need to set a new stream since we have read it
            return new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(byteOut.toByteArray()))
                    .build();
        }
    });

    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.getUrl("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl)
            .setMethod(ParseHttpRequest.Method.GET).build();

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    // Make sure the response we get is ungziped by OkHttp library
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals("content".getBytes(), content);
    // Make sure interceptor is called
    assertTrue(done.tryAcquire(10, TimeUnit.SECONDS));

    server.shutdown();
}

From source file:org.apache.sshd.common.forward.PortForwardingLoadTest.java

@Test
@SuppressWarnings("checkstyle:nestedtrydepth")
public void testLocalForwardingPayload() throws Exception {
    final int numIterations = 100;
    final String payloadTmpData = "This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. This is significantly longer Test Data. This is significantly "
            + "longer Test Data. ";
    StringBuilder sb = new StringBuilder(payloadTmpData.length() * 1000);
    for (int i = 0; i < 1000; i++) {
        sb.append(payloadTmpData);//  www . ja v a2  s  .c  om
    }
    final String payload = sb.toString();

    Session session = createSession();
    try (ServerSocket ss = new ServerSocket()) {
        ss.setReuseAddress(true);
        ss.bind(new InetSocketAddress((InetAddress) null, 0));
        int forwardedPort = ss.getLocalPort();
        int sinkPort = session.setPortForwardingL(0, TEST_LOCALHOST, forwardedPort);
        final AtomicInteger conCount = new AtomicInteger(0);
        final Semaphore iterationsSignal = new Semaphore(0);
        Thread tAcceptor = new Thread(getCurrentTestName() + "Acceptor") {
            @SuppressWarnings("synthetic-access")
            @Override
            public void run() {
                try {
                    byte[] buf = new byte[8192];
                    log.info("Started...");
                    for (int i = 0; i < numIterations; ++i) {
                        try (Socket s = ss.accept()) {
                            conCount.incrementAndGet();

                            try (InputStream sockIn = s.getInputStream();
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

                                while (baos.size() < payload.length()) {
                                    int l = sockIn.read(buf);
                                    if (l < 0) {
                                        break;
                                    }
                                    baos.write(buf, 0, l);
                                }

                                assertEquals("Mismatched received data at iteration #" + i, payload,
                                        baos.toString());

                                try (InputStream inputCopy = new ByteArrayInputStream(baos.toByteArray());
                                        OutputStream sockOut = s.getOutputStream()) {

                                    while (true) {
                                        int l = sockIn.read(buf);
                                        if (l < 0) {
                                            break;
                                        }
                                        sockOut.write(buf, 0, l);
                                    }
                                }
                            }
                        }
                        log.info("Finished iteration {}", i);
                        iterationsSignal.release();
                    }
                    log.info("Done");
                } catch (Exception e) {
                    log.error("Failed to complete run loop", e);
                }
            }
        };
        tAcceptor.start();
        Thread.sleep(TimeUnit.SECONDS.toMillis(1L));

        byte[] buf = new byte[8192];
        byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
        for (int i = 0; i < numIterations; i++) {
            log.info("Iteration {}", i);
            try (Socket s = new Socket(TEST_LOCALHOST, sinkPort); OutputStream sockOut = s.getOutputStream()) {

                s.setSoTimeout((int) FactoryManager.DEFAULT_NIO2_MIN_WRITE_TIMEOUT);

                sockOut.write(bytes);
                sockOut.flush();

                try (InputStream sockIn = s.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) {
                    while (baos.size() < payload.length()) {
                        int l = sockIn.read(buf);
                        if (l < 0) {
                            break;
                        }
                        baos.write(buf, 0, l);
                    }
                    assertEquals("Mismatched payload at iteration #" + i, payload, baos.toString());
                }
            } catch (Exception e) {
                log.error("Error in iteration #" + i, e);
            }
        }

        try {
            assertTrue("Failed to await pending iterations=" + numIterations,
                    iterationsSignal.tryAcquire(numIterations, numIterations, TimeUnit.SECONDS));
        } finally {
            session.delPortForwardingL(sinkPort);
        }

        ss.close();
        tAcceptor.join(TimeUnit.SECONDS.toMillis(11L));
    } finally {
        session.disconnect();
    }
}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

/**
 * Called when the activity is first created.
 *//*from  www .j  a  v a  2  s .  c o  m*/
@Override
protected void onCreate(Bundle load) {
    try {
        super.onCreate(load);
    } catch (NullPointerException exceptions) {
        // Unrecoverable Google Maps V1 crash
        Toast.makeText(this, R.string.error_map_nullpointer, Toast.LENGTH_LONG);
    }
    setContentView(R.layout.map);
    Toolbar toolbar = (Toolbar) findViewById(R.id.support_actionbar);
    setSupportActionBar(toolbar);

    findViewById(R.id.mapScreen).setDrawingCacheEnabled(true);
    mUnits = new UnitsI18n(this);
    mLoggerServiceManager = new GPSLoggerServiceManager();

    final Semaphore calulatorSemaphore = new Semaphore(0);
    Thread calulator = new Thread("OverlayCalculator") {
        @Override
        public void run() {
            Looper.prepare();
            mHandler = new Handler();
            calulatorSemaphore.release();
            Looper.loop();
        }
    };
    calulator.start();
    try {
        calulatorSemaphore.acquire();
    } catch (InterruptedException e) {
        Log.e(this, "Failed waiting for a semaphore", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mMapView = (MapView) findViewById(R.id.myMapView);
    setupHardwareAcceleration();
    mMylocation = new FixedMyLocationOverlay(this, mMapView);
    mMapView.setBuiltInZoomControls(true);
    mMapView.setClickable(true);

    TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04),
            (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02),
            (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) };
    mSpeedtexts = speeds;
    mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed);
    mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude);
    mDistanceView = (TextView) findViewById(R.id.currentDistance);
    mFab = (FloatingActionButton) findViewById(R.id.tracking_control);
    createListeners();

    if (load != null) {
        onRestoreInstanceState(load);
    }
    if (getIntent() != null) {
        handleIntentData(getIntent());
    }
}

From source file:org.apache.bookkeeper.tools.perf.dlog.PerfWriter.java

void write(List<DistributedLogManager> logs, double writeRate, int maxOutstandingBytesForThisThread,
        long numRecordsForThisThread, long numBytesForThisThread) throws Exception {
    log.info(/*  ww w  .j  a va 2  s  .  co m*/
            "Write thread started with : logs = {}, rate = {},"
                    + " num records = {}, num bytes = {}, max outstanding bytes = {}",
            logs.stream().map(l -> l.getStreamName()).collect(Collectors.toList()), writeRate,
            numRecordsForThisThread, numBytesForThisThread, maxOutstandingBytesForThisThread);

    List<CompletableFuture<AsyncLogWriter>> writerFutures = logs.stream()
            .map(manager -> manager.openAsyncLogWriter()).collect(Collectors.toList());
    List<AsyncLogWriter> writers = result(FutureUtils.collect(writerFutures));

    long txid = writers.stream().mapToLong(writer -> writer.getLastTxId()).max().orElse(0L);
    txid = Math.max(0L, txid);

    RateLimiter limiter;
    if (writeRate > 0) {
        limiter = RateLimiter.create(writeRate);
    } else {
        limiter = null;
    }
    final Semaphore semaphore;
    if (maxOutstandingBytesForThisThread > 0) {
        semaphore = new Semaphore(maxOutstandingBytesForThisThread);
    } else {
        semaphore = null;
    }

    // Acquire 1 second worth of records to have a slower ramp-up
    if (limiter != null) {
        limiter.acquire((int) writeRate);
    }

    long totalWritten = 0L;
    long totalBytesWritten = 0L;
    final int numLogs = logs.size();
    while (true) {
        for (int i = 0; i < numLogs; i++) {
            if (numRecordsForThisThread > 0 && totalWritten >= numRecordsForThisThread) {
                markPerfDone();
            }
            if (numBytesForThisThread > 0 && totalBytesWritten >= numBytesForThisThread) {
                markPerfDone();
            }
            if (null != semaphore) {
                semaphore.acquire(payload.length);
            }

            totalWritten++;
            totalBytesWritten += payload.length;
            if (null != limiter) {
                limiter.acquire(payload.length);
            }
            final long sendTime = System.nanoTime();
            writers.get(i).write(new LogRecord(++txid, Unpooled.wrappedBuffer(payload))).thenAccept(dlsn -> {
                if (null != semaphore) {
                    semaphore.release(payload.length);
                }

                recordsWritten.increment();
                bytesWritten.add(payload.length);

                long latencyMicros = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                recorder.recordValue(latencyMicros);
                cumulativeRecorder.recordValue(latencyMicros);
            }).exceptionally(cause -> {
                log.warn("Error at writing records", cause);
                System.exit(-1);
                return null;
            });
        }
    }
}