List of usage examples for java.util.concurrent.locks Condition await
void await() throws InterruptedException;
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 . j a v a 2s. c om * @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 www.j a va 2s. 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 w w . ja va2 s .co m*/ */ private void acquireSavingLock() throws PageSaveTiemoutExcetpion { try { //maybe it is performance bottleneck: all saving page thread must acquired SavingLock, although for different page //it just acquired lock and return, but at least, it is single thread process. saveDraftLock.lock(); String username = getUsername(); Condition cond = saveDraftLockMap.get(username); if (cond == null) { //success acquired lock cond = saveDraftLock.newCondition(); saveDraftLockMap.put(username, cond); } else { log.info("Draft save can not acquire lock. Username " + username); //60 seconds, this thread will be interrupted and throw TimeOutException. ThreadInterruptManager.addThread(Thread.currentThread(), SAVE_PAGE_TIMEOUT); try { cond.await(); } catch (InterruptedException e) { log.info("Save draft concurrent interrupted"); throw new PageSaveTiemoutExcetpion(); } } } finally { saveDraftLock.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 w w . j ava 2 s . co 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>See {@link #testAsyncSuccess()}.</p> *///from w w w .j a va 2 s. co m 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> * // ww w . jav a 2 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> * // w w w .j a v a2 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 a successful asynchronous request where the implementation of the * {@link AsyncHandler#onSuccess(HttpResponse, Object)} callback throws an exception.</p> * /*from w ww . j a v a 2s. 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>Tests an erroneous asynchronous request where the implementation of the * {@link AsyncHandler#onError(Exception)} callback throws an exception.</p> * // w w w .j av a 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: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 ww . ja v a 2 s . co 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 }