Example usage for java.util.concurrent.locks Condition signal

List of usage examples for java.util.concurrent.locks Condition signal

Introduction

In this page you can find the example usage for java.util.concurrent.locks Condition signal.

Prototype

void signal();

Source Link

Document

Wakes up one waiting thread.

Usage

From source file:Main.java

/**
 * signal a condition//from www .  j a v a 2 s .  c  o  m
 * @param lock
 * @param cond
 */
public static void signal(ReentrantLock lock, Condition cond) {
    lock.lock();
    try {
        cond.signal();
    } finally {
        lock.unlock();
    }
}

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//from w  w w. ja v a 2  s.com
 * @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 v a2s  .  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:com.edgenius.wiki.service.impl.DraftSavingLockInterceptor.java

/**
 *//*from w  ww.ja v  a  2 s.c o  m*/
private void releaseLock() {

    String username = getUsername();
    Condition cond = null;
    cond = saveDraftLockMap.remove(username);

    if (cond != null) {
        try {
            saveDraftLock.lock();
            cond.signal();
        } catch (Exception e) {
            log.warn(username + " throw exception when send condition signal:" + e);
        } finally {
            saveDraftLock.unlock();
        }
    }
    log.info("Draft lock for user " + username + " is released");
}

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> 
 *  //w  w w .j  av  a 2 s .  c o m
 * @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   w  w  w. j  a  v a2  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#onError(Exception)}.</p>
 *  //from   ww w .ja  va2  s.  c  o  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 asynchronous request execution with @{@link Async} and 
 * {@link AsyncHandler#onFailure(HttpResponse)}.</p>
 *  //from  ww  w .  j  av  a 2  s  .c o m
 * @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 an erroneous asynchronous request where the implementation of the 
 * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p>
 *  /*w  w  w .  jav a 2 s  .c om*/
 * @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: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>
 *  /* w  w  w .j  ava  2s .c om*/
 * @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
}