Search in sources :

Example 51 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class BombedProgressIndicator method runBombed.

/**
   * @return whether the indicator was canceled during runnable execution.
   */
public boolean runBombed(final Runnable runnable) {
    myThread = Thread.currentThread();
    final Semaphore canStart = new Semaphore();
    canStart.down();
    final Semaphore finished = new Semaphore();
    finished.down();
    // ProgressManager invokes indicator.checkCanceled only when there's at least one canceled indicator. So we have to create a mock one
    // on an unrelated thread and cancel it immediately.
    Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> {
        final ProgressIndicatorBase mockIndicator = new ProgressIndicatorBase();
        ProgressManager.getInstance().runProcess(() -> {
            mockIndicator.cancel();
            canStart.up();
            finished.waitFor();
            try {
                ProgressManager.checkCanceled();
                TestCase.fail();
            } catch (ProcessCanceledException ignored) {
            }
        }, mockIndicator);
    });
    ProgressManager.getInstance().runProcess(() -> {
        canStart.waitFor();
        try {
            runnable.run();
        } catch (ProcessCanceledException ignore) {
        } finally {
            finished.up();
        }
    }, this);
    try {
        future.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
    return isCanceled();
}
Also used : ProgressIndicatorBase(com.intellij.openapi.progress.util.ProgressIndicatorBase) AbstractProgressIndicatorBase(com.intellij.openapi.progress.util.AbstractProgressIndicatorBase) Semaphore(com.intellij.util.concurrency.Semaphore) ExecutionException(java.util.concurrent.ExecutionException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 52 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class BaseCompilerTestCase method compile.

private CompilationLog compile(final Consumer<CompileStatusNotification> action) {
    final Ref<CompilationLog> result = Ref.create(null);
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    final List<String> generatedFilePaths = new ArrayList<>();
    getCompilerManager().addCompilationStatusListener(new CompilationStatusAdapter() {

        @Override
        public void fileGenerated(String outputRoot, String relativePath) {
            generatedFilePaths.add(relativePath);
        }
    }, getTestRootDisposable());
    UIUtil.invokeAndWaitIfNeeded((Runnable) () -> {
        final CompileStatusNotification callback = new CompileStatusNotification() {

            @Override
            public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
                try {
                    if (aborted) {
                        Assert.fail("compilation aborted");
                    }
                    ExitStatus status = CompileDriver.getExternalBuildExitStatus(compileContext);
                    result.set(new CompilationLog(status == ExitStatus.UP_TO_DATE, generatedFilePaths, compileContext.getMessages(CompilerMessageCategory.ERROR), compileContext.getMessages(CompilerMessageCategory.WARNING)));
                } finally {
                    semaphore.up();
                }
            }
        };
        PlatformTestUtil.saveProject(myProject);
        CompilerTestUtil.saveApplicationSettings();
        action.accept(callback);
    });
    final long start = System.currentTimeMillis();
    while (!semaphore.waitFor(10)) {
        if (System.currentTimeMillis() - start > 5 * 60 * 1000) {
            throw new RuntimeException("timeout");
        }
        if (SwingUtilities.isEventDispatchThread()) {
            UIUtil.dispatchAllInvocationEvents();
        }
    }
    if (SwingUtilities.isEventDispatchThread()) {
        UIUtil.dispatchAllInvocationEvents();
    }
    return result.get();
}
Also used : Semaphore(com.intellij.util.concurrency.Semaphore) ExitStatus(com.intellij.compiler.impl.ExitStatus)

Example 53 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class RunConfigurationBeforeRunProvider method doRunTask.

public static boolean doRunTask(final String executorId, final ExecutionEnvironment environment, ProgramRunner<?> runner) {
    final Semaphore targetDone = new Semaphore();
    final Ref<Boolean> result = new Ref<>(false);
    final Disposable disposable = Disposer.newDisposable();
    environment.getProject().getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() {

        @Override
        public void processStartScheduled(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
            if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                targetDone.down();
            }
        }

        @Override
        public void processNotStarted(@NotNull final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) {
            if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                Boolean skipRun = environment.getUserData(ExecutionManagerImpl.EXECUTION_SKIP_RUN);
                if (skipRun != null && skipRun) {
                    result.set(true);
                }
                targetDone.up();
            }
        }

        @Override
        public void processTerminated(@NotNull String executorIdLocal, @NotNull ExecutionEnvironment environmentLocal, @NotNull ProcessHandler handler, int exitCode) {
            if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) {
                result.set(exitCode == 0);
                targetDone.up();
            }
        }
    });
    try {
        ApplicationManager.getApplication().invokeAndWait(() -> {
            try {
                runner.execute(environment);
            } catch (ExecutionException e) {
                targetDone.up();
                LOG.error(e);
            }
        }, ModalityState.NON_MODAL);
    } catch (Exception e) {
        LOG.error(e);
        Disposer.dispose(disposable);
        return false;
    }
    targetDone.waitFor();
    Disposer.dispose(disposable);
    return result.get();
}
Also used : Disposable(com.intellij.openapi.Disposable) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) Semaphore(com.intellij.util.concurrency.Semaphore) Ref(com.intellij.openapi.util.Ref) ProcessHandler(com.intellij.execution.process.ProcessHandler)

Example 54 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class ValueDescriptorImpl method getValue.

@Override
public Value getValue() {
    // to keep temporary objects
    if (Patches.IBM_JDK_DISABLE_COLLECTION_BUG) {
        final EvaluationContextImpl evalContext = myStoredEvaluationContext;
        if (evalContext != null && !evalContext.getSuspendContext().isResumed() && myValue instanceof ObjectReference && VirtualMachineProxyImpl.isCollected((ObjectReference) myValue)) {
            final Semaphore semaphore = new Semaphore();
            semaphore.down();
            evalContext.getDebugProcess().getManagerThread().invoke(new SuspendContextCommandImpl(evalContext.getSuspendContext()) {

                @Override
                public void contextAction() throws Exception {
                    // re-setting the context will cause value recalculation
                    try {
                        setContext(myStoredEvaluationContext);
                    } finally {
                        semaphore.up();
                    }
                }

                @Override
                protected void commandCancelled() {
                    semaphore.up();
                }
            });
            semaphore.waitFor();
        }
    }
    assertValueReady();
    return myValue;
}
Also used : EvaluationContextImpl(com.intellij.debugger.engine.evaluation.EvaluationContextImpl) SuspendContextCommandImpl(com.intellij.debugger.engine.events.SuspendContextCommandImpl) Semaphore(com.intellij.util.concurrency.Semaphore) EvaluateException(com.intellij.debugger.engine.evaluation.EvaluateException)

Example 55 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class PsiDocumentManagerBase method commitAndRunReadAction.

@Override
public void commitAndRunReadAction(@NotNull final Runnable runnable) {
    final Application application = ApplicationManager.getApplication();
    if (SwingUtilities.isEventDispatchThread()) {
        commitAllDocuments();
        runnable.run();
        return;
    }
    if (ApplicationManager.getApplication().isReadAccessAllowed()) {
        LOG.error("Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock otherwise. " + Thread.currentThread());
    }
    while (true) {
        boolean executed = application.runReadAction((Computable<Boolean>) () -> {
            if (myUncommittedDocuments.isEmpty()) {
                runnable.run();
                return true;
            }
            return false;
        });
        if (executed)
            break;
        final Semaphore semaphore = new Semaphore();
        semaphore.down();
        application.invokeLater(() -> {
            if (myProject.isDisposed()) {
                // committedness doesn't matter anymore; give clients a chance to do checkCanceled
                semaphore.up();
                return;
            }
            performWhenAllCommitted(() -> semaphore.up());
        }, ModalityState.any());
        semaphore.waitFor();
    }
}
Also used : Semaphore(com.intellij.util.concurrency.Semaphore)

Aggregations

Semaphore (com.intellij.util.concurrency.Semaphore)74 Ref (com.intellij.openapi.util.Ref)10 Project (com.intellij.openapi.project.Project)8 IOException (java.io.IOException)8 Nullable (org.jetbrains.annotations.Nullable)8 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)7 NotNull (org.jetbrains.annotations.NotNull)7 Test (org.junit.Test)7 VcsFileRevision (com.intellij.openapi.vcs.history.VcsFileRevision)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 ProcessEvent (com.intellij.execution.process.ProcessEvent)5 File (java.io.File)5 ProcessAdapter (com.intellij.execution.process.ProcessAdapter)4 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)4 Disposable (com.intellij.openapi.Disposable)4 Application (com.intellij.openapi.application.Application)4 Task (com.intellij.openapi.progress.Task)4 VcsAbstractHistorySession (com.intellij.openapi.vcs.history.VcsAbstractHistorySession)4 VcsAppendableHistorySessionPartner (com.intellij.openapi.vcs.history.VcsAppendableHistorySessionPartner)4 VcsHistoryProvider (com.intellij.openapi.vcs.history.VcsHistoryProvider)4