Search in sources :

Example 16 with Semaphore

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

the class ActionCallback method waitFor.

public boolean waitFor(long msTimeout) {
    if (isProcessed()) {
        return true;
    }
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    doWhenProcessed(() -> semaphore.up());
    try {
        if (msTimeout == -1) {
            semaphore.waitForUnsafe();
        } else if (!semaphore.waitForUnsafe(msTimeout)) {
            reject("Time limit exceeded");
            return false;
        }
    } catch (InterruptedException e) {
        reject(e.getMessage());
        return false;
    }
    return true;
}
Also used : Semaphore(com.intellij.util.concurrency.Semaphore)

Example 17 with Semaphore

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

the class CompileStepBeforeRun method doMake.

static boolean doMake(final Project myProject, final RunConfiguration configuration, final ExecutionEnvironment env, final boolean ignoreErrors, final boolean forceMakeProject) {
    if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
        return true;
    }
    if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase) configuration).excludeCompileBeforeLaunchOption()) {
        return true;
    }
    final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption) configuration;
    final Ref<Boolean> result = new Ref<>(Boolean.FALSE);
    try {
        final Semaphore done = new Semaphore();
        done.down();
        final ProjectTaskNotification callback = new ProjectTaskNotification() {

            public void finished(@NotNull ProjectTaskResult executionResult) {
                if ((executionResult.getErrors() == 0 || ignoreErrors) && !executionResult.isAborted()) {
                    result.set(Boolean.TRUE);
                }
                done.up();
            }
        };
        TransactionGuard.submitTransaction(myProject, () -> {
            ProjectTask projectTask;
            Object sessionId = ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env);
            final ProjectTaskManager projectTaskManager = ProjectTaskManager.getInstance(myProject);
            if (forceMakeProject) {
                // user explicitly requested whole-project make
                projectTask = projectTaskManager.createAllModulesBuildTask(true, myProject);
            } else {
                final Module[] modules = runConfiguration.getModules();
                if (modules.length > 0) {
                    for (Module module : modules) {
                        if (module == null) {
                            LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" + runConfiguration.getClass().getName());
                        }
                    }
                    projectTask = projectTaskManager.createModulesBuildTask(modules, true, true, true);
                } else {
                    projectTask = projectTaskManager.createAllModulesBuildTask(true, myProject);
                }
            }
            if (!myProject.isDisposed()) {
                projectTaskManager.run(new ProjectTaskContext(sessionId, configuration), projectTask, callback);
            } else {
                done.up();
            }
        });
        done.waitFor();
    } catch (Exception e) {
        return false;
    }
    return result.get();
}
Also used : Semaphore(com.intellij.util.concurrency.Semaphore) NotNull(org.jetbrains.annotations.NotNull) RunConfigurationBase(com.intellij.execution.configurations.RunConfigurationBase) Ref(com.intellij.openapi.util.Ref) RunProfileWithCompileBeforeLaunchOption(com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption) Module(com.intellij.openapi.module.Module)

Example 18 with Semaphore

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

the class JsonSchemaReadTest method doTestSchemaReadNotHung.

private void doTestSchemaReadNotHung(final File file) throws IOException {
    // because of threading
    if (Runtime.getRuntime().availableProcessors() < 2)
        return;
    Assert.assertTrue(file.exists());
    final AtomicBoolean done = new AtomicBoolean();
    final AtomicReference<IOException> error = new AtomicReference<>();
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    final Thread thread = new Thread(() -> {
        try {
            ApplicationManager.getApplication().runReadAction((ThrowableComputable<JsonSchemaObject, IOException>) () -> getSchemaObject(file));
            done.set(true);
        } catch (IOException e) {
            error.set(e);
        } finally {
            semaphore.up();
        }
    }, getClass().getName() + ": read test json schema " + file.getName());
    thread.setDaemon(true);
    try {
        thread.start();
        semaphore.waitFor(TimeUnit.SECONDS.toMillis(120));
        if (error.get() != null)
            throw error.get();
        Assert.assertTrue("Reading test schema hung!", done.get());
    } finally {
        thread.interrupt();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) Semaphore(com.intellij.util.concurrency.Semaphore)

Example 19 with Semaphore

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

the class ApplicationImpl method runProcessWithProgressSynchronouslyInReadAction.

@Override
public boolean runProcessWithProgressSynchronouslyInReadAction(@Nullable final Project project, @NotNull final String progressTitle, final boolean canBeCanceled, final String cancelText, final JComponent parentComponent, @NotNull final Runnable process) {
    assertIsDispatchThread();
    boolean writeAccessAllowed = isWriteAccessAllowed();
    if (// Disallow running process in separate thread from under write action.
    writeAccessAllowed) // The thread will deadlock trying to get read action otherwise.
    {
        throw new IncorrectOperationException("Starting process with progress from within write action makes no sense");
    }
    final ProgressWindow progress = new ProgressWindow(canBeCanceled, false, project, parentComponent, cancelText);
    // in case of abrupt application exit when 'ProgressManager.getInstance().runProcess(process, progress)' below
    // does not have a chance to run, and as a result the progress won't be disposed
    Disposer.register(this, progress);
    progress.setTitle(progressTitle);
    final Semaphore readActionAcquired = new Semaphore();
    readActionAcquired.down();
    final Semaphore modalityEntered = new Semaphore();
    modalityEntered.down();
    executeOnPooledThread(() -> {
        try {
            ApplicationManager.getApplication().runReadAction(() -> {
                readActionAcquired.up();
                modalityEntered.waitFor();
                ProgressManager.getInstance().runProcess(process, progress);
            });
        } catch (ProcessCanceledException e) {
            progress.cancel();
        // ok to ignore.
        } catch (RuntimeException e) {
            progress.cancel();
            throw e;
        }
    });
    readActionAcquired.waitFor();
    progress.startBlocking(modalityEntered::up);
    LOG.assertTrue(!progress.isRunning());
    return !progress.isCanceled();
}
Also used : ProgressWindow(com.intellij.openapi.progress.util.ProgressWindow) Semaphore(com.intellij.util.concurrency.Semaphore)

Example 20 with Semaphore

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

the class ApplicationImplTest method testSuspendWriteActionDelaysForeignReadActions.

public void testSuspendWriteActionDelaysForeignReadActions() throws Exception {
    Semaphore mayStartForeignRead = new Semaphore();
    mayStartForeignRead.down();
    List<Future> futures = new ArrayList<>();
    ApplicationImpl app = (ApplicationImpl) ApplicationManager.getApplication();
    List<String> log = Collections.synchronizedList(new ArrayList<>());
    futures.add(app.executeOnPooledThread(() -> {
        assertTrue(mayStartForeignRead.waitFor(1000));
        ReadAction.run(() -> log.add("foreign read"));
    }));
    safeWrite(() -> {
        log.add("write started");
        app.executeSuspendingWriteAction(ourProject, "", () -> {
            app.invokeAndWait(() -> futures.add(app.executeOnPooledThread(() -> ReadAction.run(() -> log.add("foreign read")))));
            mayStartForeignRead.up();
            TimeoutUtil.sleep(50);
            ReadAction.run(() -> log.add("progress read"));
            app.invokeAndWait(() -> WriteAction.run(() -> log.add("nested write")));
            waitForFuture(app.executeOnPooledThread(() -> ReadAction.run(() -> log.add("forked read"))));
        });
        log.add("write finished");
    });
    futures.forEach(ApplicationImplTest::waitForFuture);
    assertOrderedEquals(log, "write started", "progress read", "nested write", "forked read", "write finished", "foreign read", "foreign read");
}
Also used : ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) 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