Java Code Examples for com.intellij.util.concurrency.Semaphore#waitFor()

The following examples show how to use com.intellij.util.concurrency.Semaphore#waitFor() . 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: 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 2
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 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: 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 8
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 9
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 10
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 11
Source File: PotemkinProgress.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void ensureBackgroundThreadStarted(@Nonnull Runnable action) {
  Semaphore started = new Semaphore();
  started.down();
  myApp.executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> {
    started.up();
    action.run();
  }, this));

  started.waitFor();
}
 
Example 12
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();
    }
  }
}
 
Example 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void awaitWithCheckCanceled(@Nonnull Semaphore semaphore, @Nullable ProgressIndicator indicator) {
  while (!semaphore.waitFor(10)) {
    checkCancelledEvenWithPCEDisabled(indicator);
  }
}