Example usage for java.util.concurrent Semaphore tryAcquire

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

Introduction

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

Prototype

public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been Thread#interrupt interrupted .

Usage

From source file:org.jahia.services.render.filter.cache.LegacyAclCacheKeyPartGenerator.java

@SuppressWarnings("unchecked")
private Map<String, Set<String>> getPrincipalAcl(final String aclKey, final String siteKey)
        throws RepositoryException {

    final String cacheKey = siteKey != null ? aclKey + ":" + siteKey : aclKey;
    Element element = cache.get(cacheKey);
    if (element == null) {
        Semaphore semaphore = processings.get(cacheKey);
        if (semaphore == null) {
            semaphore = new Semaphore(1);
            processings.putIfAbsent(cacheKey, semaphore);
        }/*  w w w.ja  v a  2s .co  m*/
        try {
            semaphore.tryAcquire(500, TimeUnit.MILLISECONDS);
            element = cache.get(cacheKey);
            if (element != null) {
                return (Map<String, Set<String>>) element.getObjectValue();
            }

            logger.debug("Getting ACL for {}", cacheKey);
            long l = System.currentTimeMillis();

            Map<String, Set<String>> map = template.doExecuteWithSystemSessionAsUser(null,
                    Constants.LIVE_WORKSPACE, null, new JCRCallback<Map<String, Set<String>>>() {

                        @Override
                        public Map<String, Set<String>> doInJCR(JCRSessionWrapper session)
                                throws RepositoryException {
                            Query query = session.getWorkspace().getQueryManager()
                                    .createQuery("select * from [jnt:ace] as ace where ace.[j:principal] = '"
                                            + JCRContentUtils.sqlEncode(aclKey) + "'", Query.JCR_SQL2);
                            QueryResult queryResult = query.execute();
                            NodeIterator rowIterator = queryResult.getNodes();

                            Map<String, Set<String>> mapGranted = new ConcurrentHashMap<String, Set<String>>();
                            Map<String, Set<String>> mapDenied = new LinkedHashMap<String, Set<String>>();

                            while (rowIterator.hasNext()) {
                                JCRNodeWrapper node = (JCRNodeWrapper) rowIterator.next();
                                if (siteKey != null && !node.getResolveSite().getName().equals(siteKey)) {
                                    continue;
                                }
                                String path = node.getParent().getParent().getPath();
                                Set<String> foundRoles = new HashSet<String>();
                                boolean granted = node.getProperty("j:aceType").getString().equals("GRANT");
                                Value[] roles = node.getProperty(Constants.J_ROLES).getValues();
                                for (Value r : roles) {
                                    String role = r.getString();
                                    if (!foundRoles.contains(role)) {
                                        foundRoles.add(role);
                                    }
                                }
                                if (path.equals("/")) {
                                    path = "";
                                }
                                if (granted) {
                                    mapGranted.put(path, foundRoles);
                                } else {
                                    mapDenied.put(path, foundRoles);
                                }
                            }
                            for (String deniedPath : mapDenied.keySet()) {
                                String grantedPath = deniedPath;
                                while (grantedPath.length() > 0) {
                                    grantedPath = StringUtils.substringBeforeLast(grantedPath, "/");
                                    if (mapGranted.containsKey(grantedPath)) {
                                        Collection<String> intersection = CollectionUtils.intersection(
                                                mapGranted.get(grantedPath), mapDenied.get(deniedPath));
                                        for (String s : intersection) {
                                            mapGranted.get(grantedPath).add(s + " -> " + deniedPath);
                                        }
                                    }
                                }
                            }
                            return mapGranted;
                        }
                    });
            element = new Element(cacheKey, map);
            element.setEternal(true);
            cache.put(element);
            logger.debug("Getting ACL for {} took {} ms", cacheKey, System.currentTimeMillis() - l);
        } catch (InterruptedException e) {
            logger.debug(e.getMessage(), e);
        } finally {
            semaphore.release();
        }
    }
    return (Map<String, Set<String>>) element.getObjectValue();
}

From source file:org.apache.zeppelin.spark.SparkRInterpreter.java

@Override
public void open() {
    // create R script
    createRScript();//from   w  ww  . ja va 2  s .  c o  m

    int backendTimeout = Integer.parseInt(System.getenv().getOrDefault("SPARKR_BACKEND_TIMEOUT", "120"));

    // Launch a SparkR backend server for the R process to connect to; this will let it see our
    // Java system properties etc.
    ZeppelinRBackend sparkRBackend = new ZeppelinRBackend();

    Semaphore initialized = new Semaphore(0);
    Thread sparkRBackendThread = new Thread("SparkR backend") {
        @Override
        public void run() {
            sparkRBackendPort = sparkRBackend.init();
            initialized.release();
            sparkRBackend.run();
        }
    };

    sparkRBackendThread.start();

    // Wait for RBackend initialization to finish
    try {
        if (initialized.tryAcquire(backendTimeout, TimeUnit.SECONDS)) {
            // Launch R
            CommandLine cmd = CommandLine.parse(getProperty("zeppelin.sparkr.r"));
            cmd.addArgument(scriptPath, false);
            cmd.addArgument("--no-save", false);
            //      cmd.addArgument(getJavaSparkContext().version(), false);
            executor = new DefaultExecutor();
            outputStream = new ByteArrayOutputStream();
            PipedOutputStream ps = new PipedOutputStream();
            in = null;
            try {
                in = new PipedInputStream(ps);
            } catch (IOException e1) {
                throw new InterpreterException(e1);
            }
            ins = new BufferedWriter(new OutputStreamWriter(ps));

            input = new ByteArrayOutputStream();

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream, in);
            executor.setStreamHandler(streamHandler);
            executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));

            Map env = EnvironmentUtils.getProcEnvironment();

            String sparkRInterpreterObjId = sparkRBackend.put(this);
            String uberdataContextObjId = sparkRBackend.put(getUberdataContext());
            env.put("R_PROFILE_USER", scriptPath);
            env.put("SPARK_HOME", getSparkHome());
            env.put("EXISTING_SPARKR_BACKEND_PORT", String.valueOf(sparkRBackendPort));
            env.put("SPARKR_INTERPRETER_ID", sparkRInterpreterObjId);
            env.put("UBERDATA_CONTEXT_ID", uberdataContextObjId);
            logger.info("executing {} {}", env, cmd.toString());
            executor.execute(cmd, env, this);
            logger.info("executed");
            rScriptRunning = true;

        } else {
            System.err.println("SparkR backend did not initialize in " + backendTimeout + " seconds");
            System.exit(-1);
        }
    } catch (InterruptedException e) {
        new InterpreterException((e));
    } catch (IOException e) {
        new InterpreterException((e));
    }

}

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/* w  w  w .  jav  a  2  s . c om*/
        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.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 av a2  s.co m*/
    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:voldemort.store.routed.RoutedStore.java

/**
 * @return false if the operation timed out, true otherwise.
 *//* ww w .j  a  va 2s . c o m*/
private boolean blockOnPut(long startNs, Semaphore semaphore, int startingIndex, int blockCount,
        AtomicInteger successes, int successesRequired) {
    for (int i = startingIndex; i < blockCount; i++) {
        try {
            long ellapsedNs = System.nanoTime() - startNs;
            long remainingNs = (timeoutMs * Time.NS_PER_MS) - ellapsedNs;
            boolean acquiredPermit = semaphore.tryAcquire(Math.max(remainingNs, 0), TimeUnit.NANOSECONDS);
            if (!acquiredPermit) {
                logger.warn("Timed out waiting for put # " + (i + 1) + " of " + blockCount + " to succeed.");
                return false;
            }
            if (successes.get() >= successesRequired)
                break;
        } catch (InterruptedException e) {
            throw new InsufficientOperationalNodesException("Put operation interrupted", e);
        }
    }
    return true;
}

From source file:voldemort.store.routed.ThreadPoolRoutedStore.java

/**
 * @return false if the operation timed out, true otherwise.
 *///from   w w  w .  j  av  a  2s. c  om
private boolean blockOnPut(long startNs, Semaphore semaphore, int startingIndex, int blockCount,
        AtomicInteger successes, int successesRequired) {
    for (int i = startingIndex; i < blockCount; i++) {
        try {
            long ellapsedNs = System.nanoTime() - startNs;
            long remainingNs = (timeoutConfig.getOperationTimeout(VoldemortOpCode.PUT_OP_CODE) * Time.NS_PER_MS)
                    - ellapsedNs;
            boolean acquiredPermit = semaphore.tryAcquire(Math.max(remainingNs, 0), TimeUnit.NANOSECONDS);
            if (!acquiredPermit) {
                logger.warn("Timed out waiting for put # " + (i + 1) + " of " + blockCount + " to succeed.");
                return false;
            }
            if (successes.get() >= successesRequired)
                break;
        } catch (InterruptedException e) {
            throw new InsufficientOperationalNodesException("Put operation interrupted", e);
        }
    }
    return true;
}

From source file:org.paxle.core.threading.AWorkerTest.java

public void testWorkerTriggeredAndReturnToPool() throws InterruptedException {
    final ICommand command = mock(ICommand.class);
    final DummyWorker worker = new DummyWorker();
    final Semaphore waitforReturnToPool = new Semaphore(0);

    checking(new Expectations() {
        {//from  ww  w . j  av  a 2  s  .  c  o m
            // allow enqueuing and dequeueing of exactly one command
            one(inQueue).dequeue();
            will(returnValue(command));
            one(outQueue).enqueue(with(same(command)));

            // pool is not closed
            one(pool).closed();
            will(returnValue(false));

            // worker must return itself into pool
            one(pool).returnWorker(with(same(worker)));
            will(new Action() {
                public void describeTo(Description arg0) {
                }

                public Object invoke(Invocation invocation) throws Throwable {
                    waitforReturnToPool.release();
                    return null;
                }
            });
        }
    });

    // init worker
    worker.setInQueue(this.inQueue);
    worker.setOutQueue(this.outQueue);
    worker.setPool(this.pool);

    // trigger worker to dequeue and process new command
    worker.trigger();

    // wait until worker has returned itself into pool
    assertTrue(waitforReturnToPool.tryAcquire(5, TimeUnit.SECONDS));

    // terminate worker
    worker.terminate();
    assertTrue(worker.commandProcessed);
}

From source file:org.mahasen.node.MahasenNodeManager.java

/**
 * @param myContent// w  ww  .  j a v  a 2s. c  om
 */
public void insertPastContent(MahasenPropertyPastContent myContent) {

    //  String result = this.lookupDHT(resourceId);
    final Semaphore control = new Semaphore(0);

    mahasenPastTreeApp.insert(myContent, new Continuation<Boolean[], Exception>() {
        // the result is an Array of Booleans for each insert
        public void receiveResult(Boolean[] results) {

            int numSuccessfulStores = 0;

            for (int ctr = 0; ctr < results.length; ctr++) {
                if (results[ctr].booleanValue())
                    numSuccessfulStores++;
            }

            control.release();

            System.out.println(" PropertyTree successfully stored at " + +numSuccessfulStores + " locations.");
        }

        public void receiveException(Exception result) {
            System.out.println("Error storing ");
            result.printStackTrace();
            control.release();

        }
    });

    try {
        control.tryAcquire(1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        log.error("Time out while trying to insert Property tree into DHT");
    }
}

From source file:com.parse.ParseOkHttpClientTest.java

private void testParseOkHttpClientExecuteWithInterceptor(boolean isInternalInterceptorTest) throws Exception {
    // Start mock server
    server.enqueue(generateServerResponse());
    server.start();// ww w .  j  ava2s . c o  m

    ParseHttpClient client = new ParseOkHttpClient(10000, null);

    // Make ParseHttpRequest
    ParseHttpRequest parseRequest = generateClientRequest();

    final Semaphore done = new Semaphore(0);
    ParseNetworkInterceptor interceptor = new ParseNetworkInterceptor() {
        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();

            ParseHttpRequest request = chain.getRequest();

            // Verify original request
            verifyClientRequest(request);

            // Change request
            ParseHttpRequest requestAgain = generateInterceptorRequest();

            // Proceed
            ParseHttpResponse parseResponse = chain.proceed(requestAgain);

            // Verify original response
            verifyServerResponse(parseResponse);

            // Change response
            return generateInterceptorResponse();
        }
    };

    // Add interceptor
    if (isInternalInterceptorTest) {
        client.addInternalInterceptor(interceptor);
    } else {
        client.addExternalInterceptor(interceptor);
    }

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

    // Make sure interceptor is called
    assertTrue(done.tryAcquire(5, TimeUnit.SECONDS));

    RecordedRequest recordedRequest = server.takeRequest();
    // Verify request changed by interceptor
    verifyInterceptorRequest(recordedRequest);

    // Verify response changed by interceptor
    verifyInterceptorResponse(parseResponse);
}

From source file:de.zazaz.iot.bosch.indego.ifttt.IftttIndegoAdapter.java

/**
 * This is the inner run method, which does the actual work.
 *///from   w w  w  .j  av  a  2  s  . c o  m
private void runInternal() {
    CloseableHttpClient httpClient = buildHttpClient();
    Server httpServer = buildHttpServer();
    IndegoController indegoController = null;
    Semaphore semWakeup = semThreadWaker;

    boolean firstRun = true;
    boolean lastOffline = false;
    DeviceCommand lastCommand = null;
    int lastErrorCode = 0;

    try {
        while (!flagShutdown.get()) {
            if (indegoController == null) {
                LOG.info("No connection to Indego server. Creating connection.");
                indegoController = connectIndego();
                if (indegoController == null) {
                    LOG.warn("Was not able to connect to Indego server.");
                }
            }

            DeviceStateInformation currentState = null;
            if (indegoController != null) {
                try {
                    currentState = indegoController.getState();
                } catch (Exception ex) {
                    LOG.error("Exception during fetching Indego state", ex);
                    disconnect(indegoController);
                    indegoController = null;
                    try {
                        semWakeup.tryAcquire(configuration.getPollingIntervalMs(), TimeUnit.MILLISECONDS);
                    } catch (InterruptedException ex2) {
                        // Ignored
                    }
                    continue;
                }
            }

            if (indegoController != null) {
                String command = commandToExecute.getAndSet(null);
                if (command != null) {
                    LOG.info(String.format("Received command: %s", command));
                    DeviceCommand cmd = null;
                    try {
                        cmd = DeviceCommand.valueOf(command);
                    } catch (Exception ex) {
                        LOG.error(String.format("Received invalid command from IFTTT (%s)", command), ex);
                    }
                    try {
                        if (cmd != null) {
                            LOG.info(String.format("Sending command to Indego: %s", cmd));
                            indegoController.sendCommand(cmd);
                            LOG.info(String.format("Command '%s' was sent successfully", cmd));
                        }
                    } catch (Exception ex) {
                        LOG.error(String.format("Indego was not able to execute command (%s)", command), ex);
                    }
                }
            }

            boolean currentOffline = indegoController == null;
            DeviceCommand currentCommand = null;
            int currentErrorCode = 0;
            if (currentState != null) {
                currentCommand = DeviceStatus.decodeStatusCode(currentState.getState()).getAssociatedCommand();
                currentErrorCode = currentState.getError();
            }

            boolean commitOffline = firstRun;
            boolean commitCommand = firstRun;
            boolean commitErrorCode = firstRun;

            if (!firstRun) {
                String percentMowed = currentState != null ? Integer.toString(currentState.getMowed())
                        : "unknown";

                if (currentOffline != lastOffline) {
                    if (currentOffline) {
                        commitOffline = sendIfftTrigger(httpClient, configuration.getIftttOfflineEventName(),
                                "offline", "", percentMowed);
                    } else {
                        commitOffline = sendIfftTrigger(httpClient, configuration.getIftttOnlineEventName(),
                                "online", "", percentMowed);
                    }
                }

                if (currentCommand != lastCommand) {
                    String message = currentCommand != null ? currentCommand.toString() : "UNKNOWN";
                    commitCommand = sendIfftTrigger(httpClient, configuration.getIftttStateChangeEventName(),
                            message, "", percentMowed);
                }

                if (currentErrorCode != lastErrorCode) {
                    if (currentErrorCode == 0) {
                        commitErrorCode = sendIfftTrigger(httpClient,
                                configuration.getIftttErrorClearedEventName(),
                                Integer.toString(currentErrorCode), "", percentMowed);
                    } else {
                        commitErrorCode = sendIfftTrigger(httpClient, configuration.getIftttErrorEventName(),
                                Integer.toString(currentErrorCode), "Unknown error", percentMowed);
                    }
                }
            }

            if (commitOffline) {
                lastOffline = currentOffline;
            }
            if (commitCommand) {
                lastCommand = currentCommand;
            }
            if (commitErrorCode) {
                lastErrorCode = currentErrorCode;
            }
            firstRun = false;

            try {
                semWakeup.tryAcquire(configuration.getPollingIntervalMs(), TimeUnit.MILLISECONDS);
            } catch (InterruptedException ex) {
                // Ignored
            }
        }
    } finally {
        disconnect(indegoController);
        disconnect(httpServer);
        disconnect(httpClient);
    }
}