Example usage for java.util.concurrent.locks Lock newCondition

List of usage examples for java.util.concurrent.locks Lock newCondition

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock newCondition.

Prototype

Condition newCondition();

Source Link

Document

Returns a new Condition instance that is bound to this Lock instance.

Usage

From source file:Main.java

/**
 * This methods blocks until the worker is done and returns the result value of the worker.
 * If the worker was canceled an exception will be thrown.
 *
 * @param worker The worker/*  w  w w  . ja v a  2 s  .co  m*/
 * @param <T> result type of the worker
 * @return the result
 * @throws InterruptedException if the worker was canceled
 */
public static <T> T waitFor(Worker<T> worker) throws InterruptedException {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    lock.lock();
    try {
        ReadOnlyBooleanProperty doneProperty = createIsDoneProperty(worker);
        if (doneProperty.get()) {
            return worker.getValue();
        } else {
            doneProperty.addListener(e -> {
                boolean locked = lock.tryLock();
                if (locked) {
                    try {
                        condition.signal();
                    } finally {
                        lock.unlock();
                    }
                } else {
                    throw new RuntimeException("Concurreny Error");
                }
            });
            condition.await();
            return worker.getValue();
        }
    } finally {
        lock.unlock();
    }
}

From source file:Main.java

/**
 * like Platform.runLater but waits until the thread has finished
 * based on: http://www.guigarage.com/2013/01/invokeandwait-for-javafx/
 * @param r the runnable to run in a JavaFX thread
 *///from  w  w w  .  ja va 2  s .c  o  m
public static void platformRunAndWait(final Runnable r) throws Throwable {
    if (Platform.isFxApplicationThread()) {
        try {
            r.run();
        } catch (Exception e) {
            throw new ExecutionException(e);
        }
    } else {
        final Lock lock = new ReentrantLock();
        final Condition condition = lock.newCondition();
        final boolean[] done = { false };
        // to get around the requirement for final
        final Throwable[] ex = { null };
        lock.lock();
        try {

            Platform.runLater(() -> {
                lock.lock();
                try {
                    r.run();
                } catch (Throwable e) {
                    ex[0] = e;
                } finally {
                    try {
                        done[0] = true;
                        condition.signal();
                    } finally {
                        lock.unlock();
                    }
                }
            });

            while (!done[0])
                condition.await();

            if (ex[0] != null) {
                // re-throw exception from the runLater thread
                throw ex[0];
            }
        } finally {
            lock.unlock();
        }
    }
}

From source file:io.fabric8.maven.core.service.PortForwardService.java

/**
 * Forwards a port to the newest pod matching the given selector.
 * If another pod is created, it forwards connections to the new pod once it's ready.
 *///w  ww  .  ja va  2s . c o  m
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector,
        final int remotePort, final int localPort) throws Fabric8ServiceException {

    final Lock monitor = new ReentrantLock(true);
    final Condition podChanged = monitor.newCondition();
    final Pod[] nextForwardedPod = new Pod[1];

    final Thread forwarderThread = new Thread() {
        @Override
        public void run() {

            Pod currentPod = null;
            Closeable currentPortForward = null;

            try {
                monitor.lock();

                while (true) {
                    if (podEquals(currentPod, nextForwardedPod[0])) {
                        podChanged.await();
                    } else {
                        Pod nextPod = nextForwardedPod[0]; // may be null
                        try {
                            monitor.unlock();
                            // out of critical section

                            if (currentPortForward != null) {
                                log.info("Closing port-forward from pod %s",
                                        KubernetesHelper.getName(currentPod));
                                currentPortForward.close();
                                currentPortForward = null;
                            }

                            if (nextPod != null) {
                                log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
                                currentPortForward = forwardPortAsync(externalProcessLogger,
                                        KubernetesHelper.getName(nextPod), remotePort, localPort);
                            } else {
                                log.info("Waiting for a pod to become ready before starting port-forward");
                            }
                            currentPod = nextPod;
                        } finally {
                            monitor.lock();
                        }
                    }

                }

            } catch (InterruptedException e) {
                log.debug("Port-forwarding thread interrupted", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                log.warn("Error while port-forwarding to pod", e);
            } finally {
                monitor.unlock();

                if (currentPortForward != null) {
                    try {
                        currentPortForward.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    // Switching forward to the current pod if present
    Pod newPod = getNewestPod(podSelector);
    nextForwardedPod[0] = newPod;

    final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log)
            .watch(new Watcher<Pod>() {

                @Override
                public void eventReceived(Action action, Pod pod) {
                    monitor.lock();
                    try {
                        List<Pod> candidatePods;
                        if (nextForwardedPod[0] != null) {
                            candidatePods = new LinkedList<>();
                            candidatePods.add(nextForwardedPod[0]);
                            candidatePods.add(pod);
                        } else {
                            candidatePods = Collections.singletonList(pod);
                        }
                        Pod newPod = getNewestPod(candidatePods); // may be null
                        if (!podEquals(nextForwardedPod[0], newPod)) {
                            nextForwardedPod[0] = newPod;
                            podChanged.signal();
                        }
                    } finally {
                        monitor.unlock();
                    }
                }

                @Override
                public void onClose(KubernetesClientException e) {
                    // don't care
                }
            });

    forwarderThread.start();

    final Closeable handle = new Closeable() {
        @Override
        public void close() throws IOException {
            try {
                watch.close();
            } catch (Exception e) {
            }
            try {
                forwarderThread.interrupt();
                forwarderThread.join(15000);
            } catch (Exception e) {
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                handle.close();
            } catch (Exception e) {
                // suppress
            }
        }
    });

    return handle;
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a successful asynchronous request where the implementation of the 
 * {@link AsyncHandler#onSuccess(HttpResponse, Object)} callback throws an exception.</p> 
 *  //from   w w  w. j av a  2s . com
 * @since 1.3.0
 */
@Test
public final void testAsyncSuccessCallbackError() throws InterruptedException {

    String subpath = "/successcallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncSuccessCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>See {@link #testAsyncSuccess()}.</p>
 *///from www  .  ja  v a 2 s.  com
private void successScenario() throws InterruptedException {

    String subpath = "/asyncsuccess", body = "hello";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Object[] content = new Object[2];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    String result = asyncEndpoint.asyncSuccess(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String deserializedContent) {

            lock.lock();

            content[0] = httpResponse;
            content[1] = deserializedContent;

            condition.signal();
            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
    assertTrue(content[1] != null);
    assertTrue(content[1].equals(body));

    assertNull(result);
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onFailure(HttpResponse)}.</p>
 *  // w w  w .  j a  va2 s .com
 * @since 1.3.0
 */
@Test
public final void testAsyncFailure() throws InterruptedException {

    String subpath = "/asyncfailure", body = "hello";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(403).withBody(body)));

    final Object[] content = new Object[1];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailure(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            lock.lock();

            content[0] = httpResponse;
            condition.signal();

            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onError(Exception)}.</p>
 *  /* ww  w. j a  v a  2 s  .  co m*/
 * @since 1.3.0
 */
@Test
public final void testAsyncError() throws InterruptedException {

    String subpath = "/asyncerror", body = "non-JSON-content";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Object[] content = new Object[1];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            lock.lock();

            content[0] = error;
            condition.signal();

            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
    assertTrue(content[0] instanceof InvocationException);
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a failed asynchronous request where the implementation of the 
 * {@link AsyncHandler#onFailure(HttpResponse)} callback throws an exception.</p>
 *  //from  w ww.j  a va2  s.  c  o  m
 * @since 1.3.0
 */
@Test
public final void testAsyncFailureCallbackError() throws InterruptedException {

    String subpath = "/failurecallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(404)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailureCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests an erroneous asynchronous request where the implementation of the 
 * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p>
 *  // w ww  .  ja va  2  s  .  com
 * @since 1.3.0
 */
@Test
public final void testAsyncErrorCallbackError() throws InterruptedException {

    String subpath = "/errorcallbackerror", body = "non-JSON-content";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncErrorCallbackError(new AsyncHandler<User>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, User user) {
        }

        @Override
        public void onError(InvocationException error) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:org.apache.hadoop.hive.metastore.HiveMetaStore.java

/**
 * @param args/*from w w  w.  jav a  2  s  .c o m*/
 */
public static void main(String[] args) throws Throwable {
    HiveConf.setLoadMetastoreConfig(true);
    final HiveConf conf = new HiveConf(HMSHandler.class);

    HiveMetastoreCli cli = new HiveMetastoreCli(conf);
    cli.parse(args);
    final boolean isCliVerbose = cli.isVerbose();
    // NOTE: It is critical to do this prior to initializing log4j, otherwise
    // any log specific settings via hiveconf will be ignored
    Properties hiveconf = cli.addHiveconfToSystemProperties();

    // If the log4j.configuration property hasn't already been explicitly set,
    // use Hive's default log4j configuration
    if (System.getProperty("log4j.configurationFile") == null) {
        // NOTE: It is critical to do this here so that log4j is reinitialized
        // before any of the other core hive classes are loaded
        try {
            LogUtils.initHiveLog4j();
        } catch (LogInitializationException e) {
            HMSHandler.LOG.warn(e.getMessage());
        }
    }
    HiveStringUtils.startupShutdownMessage(HiveMetaStore.class, args, LOG);

    try {
        String msg = "Starting hive metastore on port " + cli.port;
        HMSHandler.LOG.info(msg);
        if (cli.isVerbose()) {
            System.err.println(msg);
        }

        // set all properties specified on the command line
        for (Map.Entry<Object, Object> item : hiveconf.entrySet()) {
            conf.set((String) item.getKey(), (String) item.getValue());
        }

        // Add shutdown hook.
        ShutdownHookManager.addShutdownHook(new Runnable() {
            @Override
            public void run() {
                String shutdownMsg = "Shutting down hive metastore.";
                HMSHandler.LOG.info(shutdownMsg);
                if (isCliVerbose) {
                    System.err.println(shutdownMsg);
                }
                if (conf.getBoolVar(ConfVars.METASTORE_METRICS)) {
                    try {
                        MetricsFactory.close();
                    } catch (Exception e) {
                        LOG.error("error in Metrics deinit: " + e.getClass().getName() + " " + e.getMessage(),
                                e);
                    }
                }
            }
        });

        //Start Metrics for Standalone (Remote) Mode
        if (conf.getBoolVar(ConfVars.METASTORE_METRICS)) {
            try {
                MetricsFactory.init(conf);
            } catch (Exception e) {
                // log exception, but ignore inability to start
                LOG.error("error in Metrics init: " + e.getClass().getName() + " " + e.getMessage(), e);
            }
        }

        Lock startLock = new ReentrantLock();
        Condition startCondition = startLock.newCondition();
        AtomicBoolean startedServing = new AtomicBoolean();
        startMetaStoreThreads(conf, startLock, startCondition, startedServing);
        startMetaStore(cli.getPort(), ShimLoader.getHadoopThriftAuthBridge(), conf, startLock, startCondition,
                startedServing);
    } catch (Throwable t) {
        // Catch the exception, log it and rethrow it.
        HMSHandler.LOG.error("Metastore Thrift Server threw an exception...", t);
        throw t;
    }
}