com.intellij.util.concurrency.Semaphore Java Examples

The following examples show how to use com.intellij.util.concurrency.Semaphore. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Isolate getCurrentIsolate() {
  final Ref<Isolate> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getIsolate(isolateRef.getId(), new GetIsolateConsumer() {
    @Override
    public void received(Isolate isolate) {
      resultRef.set(isolate);
      semaphore.up();
    }

    @Override
    public void received(Sentinel sentinel) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #2
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Library getLibrary(LibraryRef libraryRef) {
  // TODO(devoncarew): Consider changing the signature to `CompletableFuture getLibrary(LibraryRef instance)`
  // (see also the EvalOnDartLibrary implementation).

  final Ref<Library> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getLibrary(isolateRef.getId(), libraryRef.getId(), new GetLibraryConsumer() {
    @Override
    public void received(Library library) {
      resultRef.set(library);
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #3
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Script getScriptSync(@NotNull final ScriptRef scriptRef) {
  final Ref<Script> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getObject(isolateRef.getId(), scriptRef.getId(), new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #4
Source File: GotoActionModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnEdt(Runnable update) {
  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      update.run();
    }
    finally {
      semaphore.up();
    }
  }, myModality, __ -> indicator != null && indicator.isCanceled());

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
}
 
Example #5
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Isolate getCurrentIsolate() {
  final Ref<Isolate> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getIsolate(isolateRef.getId(), new GetIsolateConsumer() {
    @Override
    public void received(Isolate isolate) {
      resultRef.set(isolate);
      semaphore.up();
    }

    @Override
    public void received(Sentinel sentinel) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #6
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private Library getLibrary(LibraryRef libraryRef) {
  // TODO(devoncarew): Consider changing the signature to `CompletableFuture getLibrary(LibraryRef instance)`
  // (see also the EvalOnDartLibrary implementation).

  final Ref<Library> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getLibrary(isolateRef.getId(), libraryRef.getId(), new GetLibraryConsumer() {
    @Override
    public void received(Library library) {
      resultRef.set(library);
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });
  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #7
Source File: ScriptManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Script getScriptSync(@NotNull final ScriptRef scriptRef) {
  final Ref<Script> resultRef = Ref.create();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  vmService.getObject(isolateRef.getId(), scriptRef.getId(), new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  });

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #8
Source File: CompletionThreading.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Future<?> startThread(final ProgressIndicator progressIndicator, final Runnable runnable) {
  final Semaphore startSemaphore = new Semaphore();
  startSemaphore.down();
  Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> {
    try {
      startSemaphore.up();
      ProgressManager.checkCanceled();
      runnable.run();
    }
    catch (ProcessCanceledException ignored) {
    }
  }, progressIndicator));
  startSemaphore.waitFor();
  return future;
}
 
Example #9
Source File: ChangeListManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void freeze(@Nonnull String reason) {
  myUpdater.setIgnoreBackgroundOperation(true);
  Semaphore sem = new Semaphore();
  sem.down();

  invokeAfterUpdate(() -> {
    myUpdater.setIgnoreBackgroundOperation(false);
    myUpdater.pause();
    myFreezeName.set(reason);
    sem.up();
  }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, "", ModalityState.defaultModalityState());

  boolean free = false;
  while (!free) {
    ProgressIndicator pi = ProgressManager.getInstance().getProgressIndicator();
    if (pi != null) pi.checkCanceled();
    free = sem.waitFor(500);
  }
}
 
Example #10
Source File: UpdateRequestsQueue.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
public void waitUntilRefreshed() {
  while (true) {
    final Semaphore semaphore = new Semaphore();
    synchronized (myLock) {
      if (!myRequestSubmitted && !myRequestRunning) {
        return;
      }

      if (!myRequestRunning) {
        myScheduler.submit(new MyRunnable());
      }

      semaphore.down();
      myWaitingUpdateCompletionSemaphores.add(semaphore);
    }
    if (!semaphore.waitFor(100*1000)) {
      LOG.error("Too long VCS update");
      return;
    }
  }
}
 
Example #11
Source File: SmoothProgressAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void stop() {
  if (myOriginal.isRunning()) {
    myOriginal.stop();
  }
  else {
    myStartupAlarm.cancel(false);

    if (!myOriginalStarted && myOriginal instanceof Disposable) {
      // dispose original because start & stop were not called so original progress might not have released its resources 
      Disposer.dispose(((Disposable)myOriginal));
    }
  }

  // needed only for correct assertion of !progress.isRunning() in ApplicationImpl.runProcessWithProgressSynchroniously
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              semaphore.waitFor();
              if (myDialog != null){
                //System.out.println("myDialog.destroyProcess()");
                myDialog.close(DialogWrapper.OK_EXIT_CODE);
                myDialog = null;
              }
            }
          }
  );

  try {
    super.stop(); // should be last to not leaveModal before closing the dialog
  }
  finally {
    semaphore.up();
  }
}
 
Example #12
Source File: TransferToEDTQueue.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void waitFor() {
  final Semaphore semaphore = new Semaphore();
  semaphore.down();
  schedule(new Runnable() {
    @Override
    public void run() {
      semaphore.up();
    }
  });
  semaphore.waitFor();
}
 
Example #13
Source File: ActionUpdateEdtExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the supplied value on Swing thread, but try to avoid deadlocks by periodically performing {@link ProgressManager#checkCanceled()} in the current thread.
 * Makes sense to be used in background read actions running with a progress indicator that's canceled when a write action is about to occur.
 *
 * @see com.intellij.openapi.application.ReadAction#nonBlocking(Runnable)
 */
public static <T> T computeOnEdt(Supplier<T> supplier) {
  Application application = ApplicationManager.getApplication();
  if (application.isDispatchThread()) {
    return supplier.get();
  }

  Semaphore semaphore = new Semaphore(1);
  ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
  Ref<T> result = Ref.create();
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      if (indicator == null || !indicator.isCanceled()) {
        result.set(supplier.get());
      }
    }
    finally {
      semaphore.up();
    }
  });

  while (!semaphore.waitFor(10)) {
    if (indicator != null && indicator.isCanceled()) {
      // don't use `checkCanceled` because some smart devs might suppress PCE and end up with a deadlock like IDEA-177788
      throw new ProcessCanceledException();
    }
  }
  // check cancellation one last time, to ensure the EDT action wasn't no-op due to cancellation
  if (indicator != null && indicator.isCanceled()) {
    throw new ProcessCanceledException();
  }
  return result.get();
}
 
Example #14
Source File: ProcessHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected ProcessHandler() {
  myEventMulticaster = createEventMulticaster();
  myWaitSemaphore = new Semaphore();
  myWaitSemaphore.down();
  myAfterStartNotifiedRunner = new TasksRunner();
  myListeners.add(myAfterStartNotifiedRunner);
}
 
Example #15
Source File: PsiDocumentManagerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void commitAndRunReadAction(@Nonnull final Runnable runnable) {
  final Application application = ApplicationManager.getApplication();
  if (SwingUtilities.isEventDispatchThread()) {
    commitAllDocuments();
    runnable.run();
    return;
  }

  if (application.isReadAccessAllowed()) {
    LOG.error("Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock. " + Thread.currentThread());
  }

  while (true) {
    boolean executed = ReadAction.compute(() -> {
      if (myUncommittedDocuments.isEmpty()) {
        runnable.run();
        return true;
      }
      return false;
    });
    if (executed) break;

    TransactionId contextTransaction = TransactionGuard.getInstance().getContextTransaction();
    Semaphore semaphore = new Semaphore(1);
    application.invokeLater(() -> {
      if (myProject.isDisposed()) {
        // committedness doesn't matter anymore; give clients a chance to do checkCanceled
        semaphore.up();
        return;
      }

      performWhenAllCommitted(() -> semaphore.up(), contextTransaction);
    }, ModalityState.any());

    while (!semaphore.waitFor(10)) {
      ProgressManager.checkCanceled();
    }
  }
}
 
Example #16
Source File: CommitHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void delegateCommitToVcsThread(final GeneralCommitProcessor processor) {
  final ProgressIndicator indicator = new DelegatingProgressIndicator();

  final Semaphore endSemaphore = new Semaphore();
  endSemaphore.down();

  ChangeListManagerImpl.getInstanceImpl(myProject).executeOnUpdaterThread(new Runnable() {
    @Override
    public void run() {
      indicator.setText("Performing VCS commit...");
      try {
        ProgressManager.getInstance().runProcess(new Runnable() {
          @Override
          public void run() {
            indicator.checkCanceled();
            generalCommit(processor);
          }
        }, indicator);
      }
      finally {
        endSemaphore.up();
      }
    }
  });

  indicator.setText("Waiting for VCS background tasks to finish...");
  while (!endSemaphore.waitFor(20)) {
    indicator.checkCanceled();
  }
}
 
Example #17
Source File: UpdateRequestsQueue.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void freeSemaphores() {
  synchronized (myLock) {
    for (Semaphore semaphore : myWaitingUpdateCompletionSemaphores) {
      semaphore.up();
    }
    myWaitingUpdateCompletionSemaphores.clear();
  }
}
 
Example #18
Source File: ExecutionHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Runnable createTimelimitedExecutionProcess(final ProcessHandler processHandler, final int timeout, @Nonnull final String presentableCmdline) {
  return new Runnable() {
    private final Semaphore mySemaphore = new Semaphore();

    private final Runnable myProcessThread = new Runnable() {
      @Override
      public void run() {
        try {
          final boolean finished = processHandler.waitFor(1000 * timeout);
          if (!finished) {
            final String msg = "Timeout (" + timeout + " sec) on executing: " + presentableCmdline;
            LOG.error(msg);
            processHandler.destroyProcess();
          }
        }
        finally {
          mySemaphore.up();
        }
      }
    };

    @Override
    public void run() {
      mySemaphore.down();
      ApplicationManager.getApplication().executeOnPooledThread(myProcessThread);

      mySemaphore.waitFor();
    }
  };
}
 
Example #19
Source File: DesktopTransactionGuardImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void submitTransactionAndWait(@Nonnull final Runnable runnable) throws ProcessCanceledException {
  Application app = ApplicationManager.getApplication();
  if (app.isDispatchThread()) {
    Transaction transaction = new Transaction(runnable, getContextTransaction(), app);
    if (!canRunTransactionNow(transaction, true)) {
      String message = "Cannot run synchronous submitTransactionAndWait from invokeLater. " +
                       "Please use asynchronous submit*Transaction. " +
                       "See TransactionGuard FAQ for details.\nTransaction: " + runnable;
      if (!isWriteSafeModality(ModalityState.current())) {
        message += "\nUnsafe modality: " + ModalityState.current();
      }
      LOG.error(message);
    }
    runSyncTransaction(transaction);
    return;
  }

  if (app.isReadAccessAllowed()) {
    throw new IllegalStateException("submitTransactionAndWait should not be invoked from a read action");
  }
  final Semaphore semaphore = new Semaphore();
  semaphore.down();
  final Throwable[] exception = {null};
  submitTransaction(Disposable.newDisposable("never disposed"), getContextTransaction(), () -> {
    try {
      runnable.run();
    }
    catch (Throwable e) {
      exception[0] = e;
    }
    finally {
      semaphore.up();
    }
  });
  semaphore.waitFor();
  if (exception[0] != null) {
    throw new RuntimeException(exception[0]);
  }
}
 
Example #20
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure the current EDT activity finishes in case it requires many write actions, with each being delayed a bit
 * by background thread read action (until its first checkCanceled call). Shouldn't be called from under read action.
 */
public static void yieldToPendingWriteActions() {
  Application application = ApplicationManager.getApplication();
  if (application.isReadAccessAllowed()) {
    throw new IllegalStateException("Mustn't be called from within read action");
  }
  if (application.isDispatchThread()) {
    throw new IllegalStateException("Mustn't be called from EDT");
  }
  Semaphore semaphore = new Semaphore(1);
  application.invokeLater(semaphore::up, ModalityState.any());
  awaitWithCheckCanceled(semaphore, ProgressIndicatorProvider.getGlobalProgressIndicator());
}
 
Example #21
Source File: VmServiceWrapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) {
  assertSyncRequestAllowed();

  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  final Ref<Script> resultRef = Ref.create();

  addRequest(() -> myVmService.getObject(isolateId, scriptId, new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  }));

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #22
Source File: DartVmServiceListener.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private String evaluateExpression(final @NotNull String isolateId,
                                  final @Nullable Frame vmTopFrame,
                                  final @Nullable XExpression xExpression) {
  final String evalText = xExpression == null ? null : xExpression.getExpression();
  if (vmTopFrame == null || StringUtil.isEmptyOrSpaces(evalText)) return null;

  final Ref<String> evalResult = new Ref<>();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  myDebugProcess.getVmServiceWrapper().evaluateInFrame(isolateId, vmTopFrame, evalText, new XDebuggerEvaluator.XEvaluationCallback() {
    @Override
    public void evaluated(@NotNull final XValue result) {
      if (result instanceof DartVmServiceValue) {
        evalResult.set(getSimpleStringPresentation(((DartVmServiceValue)result).getInstanceRef()));
      }
      semaphore.up();
    }

    @Override
    public void errorOccurred(@NotNull final String errorMessage) {
      evalResult.set("Failed to evaluate log expression [" + evalText + "]: " + errorMessage);
      semaphore.up();
    }
  });

  semaphore.waitFor(1000);
  return evalResult.get();
}
 
Example #23
Source File: VmServiceWrapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) {
  assertSyncRequestAllowed();

  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  final Ref<Script> resultRef = Ref.create();

  addRequest(() -> myVmService.getObject(isolateId, scriptId, new GetObjectConsumer() {
    @Override
    public void received(Obj script) {
      resultRef.set((Script)script);
      semaphore.up();
    }

    @Override
    public void received(Sentinel response) {
      semaphore.up();
    }

    @Override
    public void onError(RPCError error) {
      semaphore.up();
    }
  }));

  semaphore.waitFor(RESPONSE_WAIT_TIMEOUT);
  return resultRef.get();
}
 
Example #24
Source File: DartVmServiceListener.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private String evaluateExpression(final @NotNull String isolateId,
                                  final @Nullable Frame vmTopFrame,
                                  final @Nullable XExpression xExpression) {
  final String evalText = xExpression == null ? null : xExpression.getExpression();
  if (vmTopFrame == null || StringUtil.isEmptyOrSpaces(evalText)) return null;

  final Ref<String> evalResult = new Ref<>();
  final Semaphore semaphore = new Semaphore();
  semaphore.down();

  myDebugProcess.getVmServiceWrapper().evaluateInFrame(isolateId, vmTopFrame, evalText, new XDebuggerEvaluator.XEvaluationCallback() {
    @Override
    public void evaluated(@NotNull final XValue result) {
      if (result instanceof DartVmServiceValue) {
        evalResult.set(getSimpleStringPresentation(((DartVmServiceValue)result).getInstanceRef()));
      }
      semaphore.up();
    }

    @Override
    public void errorOccurred(@NotNull final String errorMessage) {
      evalResult.set("Failed to evaluate log expression [" + evalText + "]: " + errorMessage);
      semaphore.up();
    }
  });

  semaphore.waitFor(1000);
  return evalResult.get();
}
 
Example #25
Source File: SequentialTaskExecutor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public <V> V queueAndWaitTask(final Callable<V> task) throws Throwable {
  final Ref<V> resultRef = new Ref<V>();
  final Ref<Throwable> throwableRef = new Ref<Throwable>();

  final Semaphore taskSemaphore = new Semaphore();
  taskSemaphore.down();

  queueTask(new Runnable() {

    @Override
    public void run() {
      try {
        resultRef.set(task.call());
      }
      catch (Throwable e) {
        throwableRef.set(e);
        LOG.error(e);
      }
      finally {
        taskSemaphore.up();
      }
    }
  });

  taskSemaphore.waitFor();

  if (!throwableRef.isNull()) {
    throw throwableRef.get();
  }

  return resultRef.get();
}
 
Example #26
Source File: RemoteServerConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void testConnection() {
  final ServerConnection connection = ServerConnectionManager.getInstance().getOrCreateConnection(myServer);
  final AtomicReference<Runnable> showResultRef = new AtomicReference<Runnable>(null);
  new Task.Modal(null, "Connecting...", true) {
    @Override
    public void run(@Nonnull ProgressIndicator indicator) {
      indicator.setIndeterminate(true);
      final Semaphore semaphore = new Semaphore();
      semaphore.down();
      connection.connect(new Runnable() {
        @Override
        public void run() {
          showResultRef.set(new Runnable() {
            @Override
            public void run() {
              if (connection.getStatus() == ConnectionStatus.CONNECTED) {
                Messages.showInfoMessage(myMainPanel, "Connection successful", "Test Connection");
              }
              else if (connection.getStatus() == ConnectionStatus.DISCONNECTED) {
                Messages.showErrorDialog(myMainPanel, "Cannot connect: " + connection.getStatusText(), "Test Connection");
              }
            }
          });
          semaphore.up();
        }
      });
      while (!indicator.isCanceled()) {
        if (semaphore.waitFor(500)) {
          break;
        }
      }
      Runnable showResult = showResultRef.get();
      if (showResult != null) {
        ApplicationManager.getApplication().invokeLater(showResult);
      }
    }
  }.queue();
}
 
Example #27
Source File: ProcessCloseUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void close(final Process process) {
  final Semaphore outerSemaphore = new Semaphore();
  outerSemaphore.down();

  final Application application = ApplicationManager.getApplication();
  application.executeOnPooledThread(new Runnable() {
    public void run() {
      try {
        final Semaphore semaphore = new Semaphore();
        semaphore.down();

        final Runnable closeRunnable = new Runnable() {
          public void run() {
            try {
              closeProcessImpl(process);
            }
            finally {
              semaphore.up();
            }
          }
        };

        final Future<?> innerFuture = application.executeOnPooledThread(closeRunnable);
        semaphore.waitFor(ourAsynchronousWaitTimeout);
        if ( ! (innerFuture.isDone() || innerFuture.isCancelled())) {
          innerFuture.cancel(true); // will call interrupt()
        }
      }
      finally {
        outerSemaphore.up();
      }
    }
  });

  // just wait
  outerSemaphore.waitFor(ourSynchronousWaitTimeout);
}
 
Example #28
Source File: LaterInvocator.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void invokeAndWait(@Nonnull final Runnable runnable, @Nonnull ModalityState modalityState) {
  LOG.assertTrue(!isDispatchThread());

  final Semaphore semaphore = new Semaphore();
  semaphore.down();
  final Ref<Throwable> exception = Ref.create();
  Runnable runnable1 = new Runnable() {
    @Override
    public void run() {
      try {
        runnable.run();
      }
      catch (Throwable e) {
        exception.set(e);
      }
      finally {
        semaphore.up();
      }
    }

    @Override
    @NonNls
    public String toString() {
      return "InvokeAndWait[" + runnable + "]";
    }
  };
  invokeLaterWithCallback(runnable1, modalityState, Conditions.FALSE, null);
  semaphore.waitFor();
  if (!exception.isNull()) {
    Throwable cause = exception.get();
    if (SystemProperties.getBooleanProperty("invoke.later.wrap.error", true)) {
      // wrap everything to keep the current thread stacktrace
      // also TC ComparisonFailure feature depends on this
      throw new RuntimeException(cause);
    }
    else {
      ExceptionUtil.rethrow(cause);
    }
  }
}
 
Example #29
Source File: LaterInvocator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static void dispatchPendingFlushes() {
  if (!isDispatchThread()) throw new IllegalStateException("Must call from EDT");

  Semaphore semaphore = new Semaphore();
  semaphore.down();
  invokeLaterWithCallback(semaphore::up, ModalityState.any(), Conditions.FALSE, null);
  while (!semaphore.isUp()) {
    UIUtil.dispatchAllInvocationEvents();
  }
}
 
Example #30
Source File: DesktopAsyncEditorLoader.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void waitForCommit(long commitDeadlineNs) {
  Document document = myEditor.getDocument();
  PsiDocumentManager pdm = PsiDocumentManager.getInstance(myProject);
  if (!pdm.isCommitted(document) && System.nanoTime() < commitDeadlineNs) {
    Semaphore semaphore = new Semaphore(1);
    pdm.performForCommittedDocument(document, semaphore::up);
    while (System.nanoTime() < commitDeadlineNs && !semaphore.waitFor(10)) {
      ProgressManager.checkCanceled();
    }
  }
}