Example usage for java.util.concurrent Semaphore release

List of usage examples for java.util.concurrent Semaphore release

Introduction

In this page you can find the example usage for java.util.concurrent Semaphore release.

Prototype

public void release() 

Source Link

Document

Releases a permit, returning it to the semaphore.

Usage

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  .j a  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.storm.daemon.DrpcServer.java

private void initClearThread() {
    clearThread = Utils.asyncLoop(new Callable() {

        @Override//  ww  w  .  ja  v  a 2 s. c o m
        public Object call() throws Exception {
            for (Map.Entry<String, InternalRequest> e : outstandingRequests.entrySet()) {
                InternalRequest internalRequest = e.getValue();
                if (Time.deltaSecs(internalRequest.startTimeSecs) > Utils
                        .getInt(conf.get(Config.DRPC_REQUEST_TIMEOUT_SECS))) {
                    String id = e.getKey();
                    Semaphore sem = internalRequest.sem;
                    if (sem != null) {
                        String func = internalRequest.function;
                        acquireQueue(func).remove(internalRequest.request);
                        LOG.warn("Timeout DRPC request id: {} start at {}", id, e.getValue());
                        sem.release();
                    }
                    cleanup(id);
                }
            }
            return getTimeoutCheckSecs();
        }
    });
}

From source file:org.novelang.outfit.shell.ProcessShell.java

private InputStreamWatcher createStandardOutputWatcher(final InputStream standardOutput,
        final Semaphore startupSemaphore) {
    return new InputStreamWatcher(standardOutput) {
        @Override// ww  w .  java 2  s. co m
        protected void interpretLine(final String line) {
            if (line != null) {
                LOGGER.debug("Standard output from ", getNickname(), ": >>> ", line);
                if ( /*startupSemaphore.availablePermits() == 0 &&*/ startupSensor.apply(line)) {
                    LOGGER.debug("Startup detected for ", getNickname(), ".");
                    startupSemaphore.release();
                }
            }
        }

        @Override
        protected void handleThrowable(final Throwable throwable) {
            handleThrowableFromProcess(throwable);
        }
    };
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

@Test
public void configureClientSSLSocketCanTimeOut() throws Exception {
    final Semaphore serverCoordination = new Semaphore(0);

    // configure a non-SSL server socket. We will connect
    // a client SSL socket to it and demonstrate that the
    // handshake times out
    final ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0));
    Thread serverThread = new Thread() {
        public void run() {
            serverCoordination.release();
            try (Socket clientSocket = serverSocket.accept()) {
                System.out.println("server thread accepted a connection");
                serverCoordination.acquire();
            } catch (Exception e) {
                System.err.println("accept failed");
                e.printStackTrace();//from w w w  . j a  va2  s. c  om
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                // ignored
            }
            System.out.println("server thread is exiting");
        }
    };
    serverThread.setName("SocketCreatorJUnitTest serverSocket thread");
    serverThread.setDaemon(true);
    serverThread.start();

    serverCoordination.acquire();

    SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER);

    int serverSocketPort = serverSocket.getLocalPort();
    try {
        Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> {
            try {
                Socket clientSocket = socketCreator.connectForClient(
                        SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000);
                clientSocket.close();
                System.err.println(
                        "client successfully connected to server but should not have been able to do so");
                return false;
            } catch (SocketTimeoutException e) {
                // we need to verify that this timed out in the handshake
                // code
                System.out.println("client connect attempt timed out - checking stack trace");
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement element : trace) {
                    if (element.getMethodName().equals("configureClientSSLSocket")) {
                        System.out.println("client connect attempt timed out in the appropriate method");
                        return true;
                    }
                }
                // it wasn't in the configuration method so we need to try again
            } catch (IOException e) {
                // server socket may not be in accept() yet, causing a connection-refused
                // exception
            }
            return false;
        });
    } finally {
        serverCoordination.release();
    }
}

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

/**
 * The save method provides the functionality to save an instance to the file system.
 * @param type The type that will be saved to the file system.
 * @return The type that was saved to the file system. The main reason for it is being returned is because
 *         there could be modifications of the object during the save process. For example, if the type does not
 *         have an identifier, then the method will generate a new identifier for the type.
 *//*from w  w w  .jav a 2 s.  c  o m*/
protected D save(final T type) {
    I id = type.getId();

    if (id == null) {
        id = (I) generateId();
        type.setId(id);
    }
    checkType(type);
    final String filename = getFilename(id);

    final Semaphore writeLock = getWriteLock(id);

    try {
        writeLock.acquire();
        fileRepositorySupport.save(type, filename);
        collection.put(id, type);
        return mapper.map(type, dtoClass);
    } catch (InterruptedException e) {
        throw new IllegalStateException("Unable to acquire the write lock", e);
    } finally {
        writeLock.release();
    }
}

From source file:com.netflix.curator.ensemble.exhibitor.TestExhibitorEnsembleProvider.java

@Test
public void testChanging() throws Exception {
    TestingServer secondServer = new TestingServer();
    try {//from   w w w  . ja va 2  s.  c o  m
        String mainConnectionString = "count=1&port=" + server.getPort() + "&server0=localhost";
        String secondConnectionString = "count=1&port=" + secondServer.getPort() + "&server0=localhost";

        final Semaphore semaphore = new Semaphore(0);
        final AtomicReference<String> connectionString = new AtomicReference<String>(mainConnectionString);
        Exhibitors exhibitors = new Exhibitors(Lists.newArrayList("foo", "bar"), 1000,
                dummyConnectionStringProvider);
        ExhibitorRestClient mockRestClient = new ExhibitorRestClient() {
            @Override
            public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception {
                semaphore.release();
                return connectionString.get();
            }
        };
        ExhibitorEnsembleProvider provider = new ExhibitorEnsembleProvider(exhibitors, mockRestClient, "/foo",
                10, new RetryOneTime(1));
        provider.pollForInitialEnsemble();

        Timing timing = new Timing().multiple(4);
        final CuratorZookeeperClient client = new CuratorZookeeperClient(provider, timing.session(),
                timing.connection(), null, new RetryOneTime(2));
        client.start();
        try {
            RetryLoop.callWithRetry(client, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    client.getZooKeeper().create("/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
                            CreateMode.PERSISTENT);
                    return null;
                }
            });

            connectionString.set(secondConnectionString);
            semaphore.drainPermits();
            semaphore.acquire();

            server.stop(); // create situation where the current zookeeper gets a sys-disconnected

            Stat stat = RetryLoop.callWithRetry(client, new Callable<Stat>() {
                @Override
                public Stat call() throws Exception {
                    return client.getZooKeeper().exists("/test", false);
                }
            });
            Assert.assertNull(stat); // it's a different server so should be null
        } finally {
            client.close();
        }
    } finally {
        IOUtils.closeQuietly(secondServer);
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

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

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();//  w  ww. j  a v a2s . c  o  m
    try {
        final InterProcessLock mutex1 = makeLock(client);
        final InterProcessLock mutex2 = makeLock(client);

        final Semaphore semaphore = new Semaphore(0);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                mutex1.acquire();
                semaphore.release();
                Thread.sleep(1000000);
                return null;
            }
        });

        service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                mutex2.acquire();
                semaphore.release();
                Thread.sleep(1000000);
                return null;
            }
        });

        Assert.assertTrue(timing.acquireSemaphore(semaphore, 1));
        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Assert.assertTrue(timing.acquireSemaphore(semaphore, 1));
    } finally {
        client.close();
    }
}

From source file:com.qwazr.search.index.IndexInstance.java

final List<BackupStatus> getBackups() throws InterruptedException {
    final Semaphore sem = schema.acquireReadSemaphore();
    try {//from ww  w .j  av  a 2s .  c  om
        return backups();
    } finally {
        if (sem != null)
            sem.release();
    }
}

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  w  w w  . ja  v a2  s  .  c om*/
    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.commoncrawl.service.listcrawler.ProxyServlet.java

private static void queueHighPriorityURLRequest(final String targetURL, final long urlFingerprint,
        final AsyncResponse responseData, final Semaphore completionSemaphore, final long timeoutInMS,
        final boolean skipHTTPFetch) {

    // first check skip fetch flag ... 
    if (skipHTTPFetch) {
        // setup an async callback ... 
        ProxyServer.getSingleton().getEventLoop().setTimer(new Timer(0, false, new Timer.Callback() {

            @Override//from   w  w w  .  j  a va 2s.  c  om
            public void timerFired(Timer timer) {
                responseData.setHttpErrorResponse(403, "Request Not Found In Cache");
                responseData.setCrawlComplete(true);
                // and set the completion semaphore ... 
                completionSemaphore.release();
            }
        }));

        return;
    }

    // 3. ok time to dispatch this request via the crawler ... 
    ProxyServer.getSingleton().queueHighPriorityURL(targetURL, urlFingerprint, new CrawlItemStatusCallback() {

        @Override
        public void crawlComplete(NIOHttpConnection connection, CrawlURL urlObject, CrawlTarget optTargetObj,
                boolean success) {
            if (!success) {
                // set failure code on url .. 
                urlObject.setLastAttemptResult((byte) CrawlURL.CrawlResult.FAILURE);
            }
            // cache the http result 
            cacheCrawlURLResult(urlObject, null);

            // if item was not timed out ... 
            if (!responseData.isCrawlComplete()) {
                // set the result data .. 
                responseData.setURLItemRespone(urlObject);
                // and set the completion semaphore ... 
                completionSemaphore.release();
            }
        }

        @Override
        public void crawlStarting(CrawlTarget target) {
            // reset start time to http request start time ...
            responseData.setStartTime(System.currentTimeMillis());
        }

    });

    // and setup a timeout timer ... 
    ProxyServer.getSingleton().getEventLoop().setTimer(new Timer(timeoutInMS, false, new Timer.Callback() {

        @Override
        public void timerFired(Timer timer) {
            // check to see if request is already complete or not 
            if (!responseData.isCrawlComplete()) {
                responseData.setHttpErrorResponse(500, "Request Timed Out");
                responseData.setCrawlComplete(true);
                // and set the completion semaphore ... 
                completionSemaphore.release();
            }
        }
    }));
}