com.intellij.util.concurrency.AppExecutorUtil Java Examples

The following examples show how to use com.intellij.util.concurrency.AppExecutorUtil. 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: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateOnPsiChanges(@Nonnull LightweightHint hint, @Nonnull Info info, @Nonnull Consumer<? super String> textConsumer, @Nonnull String oldText, @Nonnull Editor editor) {
  if (!hint.isVisible()) return;
  Disposable hintDisposable = Disposable.newDisposable("CtrlMouseHandler.TooltipProvider.updateOnPsiChanges");
  hint.addHintListener(__ -> Disposer.dispose(hintDisposable));
  myProject.getMessageBus().connect(hintDisposable).subscribe(PsiModificationTracker.TOPIC, () -> ReadAction.nonBlocking(() -> {
    try {
      DocInfo newDocInfo = info.getInfo();
      return (Runnable)() -> {
        if (newDocInfo.text != null && !oldText.equals(newDocInfo.text)) {
          updateText(newDocInfo.text, textConsumer, hint, editor);
        }
      };
    }
    catch (IndexNotReadyException e) {
      showDumbModeNotification(myProject);
      return createDisposalContinuation();
    }
  }).finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).withDocumentsCommitted(myProject).expireWith(hintDisposable).expireWhen(() -> !info.isValid(editor.getDocument()))
          .coalesceBy(hint).submit(AppExecutorUtil.getAppExecutorService()));
}
 
Example #2
Source File: ProgressIndicatorUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Run the given computation with its execution time restricted to the given amount of time in milliseconds.<p></p>
 * <p>
 * Internally, it creates a new {@link ProgressIndicator}, runs the computation with that indicator and cancels it after the the timeout.
 * The computation should call {@link ProgressManager#checkCanceled()} frequently enough, so that after the timeout has been exceeded
 * it can stop the execution by throwing {@link ProcessCanceledException}, which will be caught by this {@code withTimeout}.<p></p>
 * <p>
 * If a {@link ProcessCanceledException} happens due to any other reason (e.g. a thread's progress indicator got canceled),
 * it'll be thrown out of this method.
 *
 * @return the computation result or {@code null} if timeout has been exceeded.
 */
@Nullable
public static <T> T withTimeout(long timeoutMs, @Nonnull Computable<T> computation) {
  ProgressManager.checkCanceled();
  ProgressIndicator outer = ProgressIndicatorProvider.getGlobalProgressIndicator();
  ProgressIndicator inner = outer != null ? new SensitiveProgressWrapper(outer) : new ProgressIndicatorBase(false, false);
  AtomicBoolean canceledByTimeout = new AtomicBoolean();
  ScheduledFuture<?> cancelProgress = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    canceledByTimeout.set(true);
    inner.cancel();
  }, timeoutMs, TimeUnit.MILLISECONDS);
  try {
    return ProgressManager.getInstance().runProcess(computation, inner);
  }
  catch (ProcessCanceledException e) {
    if (canceledByTimeout.get()) {
      return null;
    }
    throw e; // canceled not by timeout
  }
  finally {
    cancelProgress.cancel(false);
  }
}
 
Example #3
Source File: AccessRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static <T> AsyncResult<T> readAsync(@RequiredReadAction @Nonnull ThrowableComputable<T, Throwable> action) {
  AsyncResult<T> result = AsyncResult.undefined();
  Application application = Application.get();
  AppExecutorUtil.getAppExecutorService().execute(() -> {
    try {
      result.setDone(application.runReadAction(action));
    }
    catch (Throwable throwable) {
      LOG.error(throwable);

      result.rejectWithThrowable(throwable);
    }
  });
  return result;
}
 
Example #4
Source File: StartupManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public final void scheduleBackgroundPostStartupActivities(@Nonnull UIAccess uiAccess) {
  if (myProject.isDisposedOrDisposeInProgress()) {
    return;
  }

  myBackgroundPostStartupScheduledFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    if (myProject.isDisposedOrDisposeInProgress()) {
      return;
    }

    List<StartupActivity.Background> activities = StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.getExtensionList();
    //StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<StartupActivity.Background>() {
    //  @Override
    //  public void extensionAdded(@Nonnull StartupActivity.Background extension, @Nonnull PluginDescriptor pluginDescriptor) {
    //    extension.runActivity(myProject);
    //  }
    //}, this);

    BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, () -> {
      for (StartupActivity activity : activities) {
        ProgressManager.checkCanceled();

        if (myProject.isDisposedOrDisposeInProgress()) {
          return;
        }

        activity.runActivity(uiAccess, myProject);
      }
    });
  }, Registry.intValue("ide.background.post.startup.activity.delay"), TimeUnit.MILLISECONDS);
}
 
Example #5
Source File: AccessRule.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static <T> AsyncResult<T> writeAsync(@RequiredWriteAction @Nonnull ThrowableComputable<T, Throwable> action) {
  ApplicationWithIntentWriteLock application = (ApplicationWithIntentWriteLock)Application.get();
  ExecutorService service = AppExecutorUtil.getAppExecutorService();
  AsyncResult<T> result = AsyncResult.undefined();
  service.execute(() -> {
    application.acquireWriteIntentLock();

    try {
      try {
        result.setDone(application.runWriteActionNoIntentLock(action));
      }
      catch (Throwable throwable) {
        LOG.error(throwable);

        result.rejectWithThrowable(throwable);
      }
    }
    finally {
      application.releaseWriteIntentLock();
    }
  });

  return result;
}
 
Example #6
Source File: ParameterInfoTaskRunnerUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @param progressTitle null means no loading panel should be shown
 */
static <T> void runTask(Project project, NonBlockingReadAction<T> nonBlockingReadAction, Consumer<T> continuationConsumer, @Nullable String progressTitle, Editor editor) {
  AtomicReference<CancellablePromise<?>> cancellablePromiseRef = new AtomicReference<>();
  Consumer<Boolean> stopAction = startProgressAndCreateStopAction(editor.getProject(), progressTitle, cancellablePromiseRef, editor);

  final VisibleAreaListener visibleAreaListener = new CancelProgressOnScrolling(cancellablePromiseRef);

  editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener);

  final Component focusOwner = getFocusOwner(project);

  cancellablePromiseRef.set(nonBlockingReadAction.finishOnUiThread(ModalityState.defaultModalityState(), continuation -> {
    CancellablePromise<?> promise = cancellablePromiseRef.get();
    if (promise != null && promise.isSucceeded() && Objects.equals(focusOwner, getFocusOwner(project))) {
      continuationConsumer.accept(continuation);
    }
  }).expireWith(editor instanceof DesktopEditorImpl ? ((DesktopEditorImpl)editor).getDisposable() : project).submit(AppExecutorUtil.getAppExecutorService()).onProcessed(ignore -> {
    stopAction.accept(false);
    editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
  }));
}
 
Example #7
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
void execute(@Nonnull BrowseMode browseMode) {
  myBrowseMode = browseMode;

  if (PsiDocumentManager.getInstance(myProject).getPsiFile(myHostEditor.getDocument()) == null) return;

  int selStart = myHostEditor.getSelectionModel().getSelectionStart();
  int selEnd = myHostEditor.getSelectionModel().getSelectionEnd();

  if (myHostOffset >= selStart && myHostOffset < selEnd) {
    disposeHighlighter();
    return;
  }

  myExecutionProgress = ReadAction.nonBlocking(() -> doExecute()).withDocumentsCommitted(myProject).expireWhen(() -> isTaskOutdated(myHostEditor))
          .finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run).submit(AppExecutorUtil.getAppExecutorService());
}
 
Example #8
Source File: AndroidUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void enable() {
  // Look for "include ':flutterModuleName'". If not found, add it and create build.gradle in the Flutter module. Then sync.
  if (verifyEligibility()) {
    makeBuildFile();
    if (errorDuringOperation.get()) return;
    addIncludeStatement();
    if (errorDuringOperation.get()) return;
    addCoeditTransformedProject(project);
    // We may have multiple Gradle sync listeners. Write the files to disk synchronously so we won't edit them twice.
    projectRoot.refresh(false, true);
    if (!projectRoot.equals(flutterModuleDir.getParent())) {
      flutterModuleDir.refresh(false, true);
    }
    AppExecutorUtil.getAppExecutorService().execute(() -> scheduleGradleSyncAfterSyncFinishes(project));
  }
}
 
Example #9
Source File: SystemUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Execute the given command line, and return the process output as one result in a future.
 * <p>
 * This is a non-blocking equivalient to {@link ExecUtil#execAndGetOutput(GeneralCommandLine)}.
 */
public static CompletableFuture<ProcessOutput> execAndGetOutput(GeneralCommandLine cmd) {
  final CompletableFuture<ProcessOutput> future = new CompletableFuture<>();

  AppExecutorUtil.getAppExecutorService().submit(() -> {
    try {
      final ProcessOutput output = ExecUtil.execAndGetOutput(cmd);
      future.complete(output);
    }
    catch (ExecutionException e) {
      future.completeExceptionally(e);
    }
  });

  return future;
}
 
Example #10
Source File: DesktopTipOfDayManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void scheduleShow(@Nonnull UIAccess uiAccess, @Nonnull Project project) {
  if (myAlreadyShow.compareAndSet(false, true)) {
    Future<?> future = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
      if (project.isDisposed()) {
        // revert state if project canceled
        myAlreadyShow.compareAndSet(true, false);
        return;
      }

      uiAccess.give(this::show);
    }, 5, TimeUnit.SECONDS);

    Disposer.register(project, () -> {
      if (!future.isDone()) {
        // task not done - it's mean, it was canceled before - reset state
        myAlreadyShow.compareAndSet(true, false);
        future.cancel(false);
      }
    });
  }
}
 
Example #11
Source File: RecentProjectPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void onAppStateChanged() {
  boolean settingsAreOK = !PowerSaveMode.isEnabled();
  boolean everythingIsOK = settingsAreOK && ApplicationManager.getApplication().isActive();
  if (myService == null && everythingIsOK) {
    myService = AppExecutorUtil.createBoundedScheduledExecutorService("CheckRecentProjectPaths Service", 2);
    for (String path : myPaths) {
      scheduleCheck(path, 0);
    }
    ApplicationManager.getApplication().invokeLater(myCallback);
  }
  if (myService != null && !everythingIsOK) {
    if (!settingsAreOK) {
      myInvalidPaths.clear();
    }
    if (!myService.isShutdown()) {
      myService.shutdown();
      myService = null;
    }
    ApplicationManager.getApplication().invokeLater(myCallback);
  }
}
 
Example #12
Source File: AndroidUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void enable() {
  // Look for "include ':flutterModuleName'". If not found, add it and create build.gradle in the Flutter module. Then sync.
  if (verifyEligibility()) {
    makeBuildFile();
    if (errorDuringOperation.get()) return;
    addIncludeStatement();
    if (errorDuringOperation.get()) return;
    addCoeditTransformedProject(project);
    // We may have multiple Gradle sync listeners. Write the files to disk synchronously so we won't edit them twice.
    projectRoot.refresh(false, true);
    if (!projectRoot.equals(flutterModuleDir.getParent())) {
      flutterModuleDir.refresh(false, true);
    }
    AppExecutorUtil.getAppExecutorService().execute(() -> scheduleGradleSyncAfterSyncFinishes(project));
  }
}
 
Example #13
Source File: SystemUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Execute the given command line, and return the process output as one result in a future.
 * <p>
 * This is a non-blocking equivalient to {@link ExecUtil#execAndGetOutput(GeneralCommandLine)}.
 */
public static CompletableFuture<ProcessOutput> execAndGetOutput(GeneralCommandLine cmd) {
  final CompletableFuture<ProcessOutput> future = new CompletableFuture<>();

  AppExecutorUtil.getAppExecutorService().submit(() -> {
    try {
      final ProcessOutput output = ExecUtil.execAndGetOutput(cmd);
      future.complete(output);
    }
    catch (ExecutionException e) {
      future.completeExceptionally(e);
    }
  });

  return future;
}
 
Example #14
Source File: RemoteExternalSystemFacadeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Schedules automatic process termination in {@code #REMOTE_GRADLE_PROCESS_TTL_IN_MS} milliseconds.
 * <p>
 * Rationale: it's possible that IJ user performs gradle related activity (e.g. import from gradle) when the works purely
 * at IJ. We don't want to keep remote process that communicates with the gradle api then.
 */
private void updateAutoShutdownTime() {
  myShutdownFuture.cancel(false);
  myShutdownFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    if (myCallsInProgressNumber.get() > 0) {
      updateAutoShutdownTime();
      return;
    }
    System.exit(0);
  }, (int)myTtlMs.get(), TimeUnit.MILLISECONDS);
}
 
Example #15
Source File: ModuleDataService.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  myFuture.cancel(false);
  if (!myProject.isInitialized()) {
    myFuture = AppExecutorUtil.getAppScheduledExecutorService()
            .schedule(new ImportModulesTask(myProject, myModules, mySynchronous), PROJECT_INITIALISATION_DELAY_MS, TimeUnit.MILLISECONDS);
    return;
  }

  importData(myModules, myProject, mySynchronous);
}
 
Example #16
Source File: AndroidUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void checkDartSupport(@NotNull Project project) {
  runAfterSyncFinishes(project, (p) -> {
    // Gradle sync-finished events are triggered before new modules have been committed. Once the condition
    // is met we still have to wait for a short while.
    AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
      Stream<Module> modules =
        Arrays.stream(FlutterModuleUtils.getModules(p)).filter(FlutterModuleUtils::declaresFlutter);
      modules.forEach((module) -> {
        if (!DartSdkLibUtil.isDartSdkEnabled(module)) {
          new EnableDartSupportForModule(module).run();
        }
      });
    }, 1, TimeUnit.SECONDS);
  });
}
 
Example #17
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void dispose() {
  fireApplicationExiting();

  ShutDownTracker.getInstance().ensureStopperThreadsFinished();

  AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService();
  service.shutdownAppScheduledExecutorService();

  super.dispose();
  Disposer.dispose(myLastDisposable); // dispose it last
}
 
Example #18
Source File: NonBlockingReadActionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void trackSubmission(@Nonnull Executor backgroundThreadExecutor, AsyncPromise<T> promise) {
  if (backgroundThreadExecutor == AppExecutorUtil.getAppExecutorService()) {
    preventTooManySubmissions(promise);
  }
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    rememberSubmissionInTests(promise);
  }
}
 
Example #19
Source File: SmoothProgressAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void start() {
  if (isRunning()) return;

  super.start();
  myOriginalStarted = false;
  myStartupAlarm = AppExecutorUtil.getAppScheduledExecutorService().schedule(myShowRequest, SHOW_DELAY, TimeUnit.MILLISECONDS);
}
 
Example #20
Source File: StatisticsSendManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void runWithDelay() {
  myFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule((Runnable)() -> {
    try {
      UsageStatisticsPersistenceComponent component = myUsageStatisticsComponent.get();
      
      sendNow(component);
    }
    finally {
      myFuture = null;
    }
  }, DELAY_IN_MIN, TimeUnit.MINUTES);
}
 
Example #21
Source File: SafeFileOutputStream.java    From consulo with Apache License 2.0 5 votes vote down vote up
public SafeFileOutputStream(@Nonnull Path target, @Nonnull String backupExt) {
  myTarget = target;
  myBackupName = myTarget.getFileName() + backupExt;
  myBackupFuture = !Files.exists(target) ? null : AppExecutorUtil.getAppExecutorService().submit(() -> {
    Path parent = myTarget.getParent();
    Path backup = parent != null ? parent.resolve(myBackupName) : Paths.get(myBackupName);
    Files.copy(myTarget, backup, BACKUP_COPY);
    return backup;
  });
  myBuffer = new BufferExposingByteArrayOutputStream();
}
 
Example #22
Source File: CoreProgressManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void checkLaterThreadsAreUnblocked() {
  try {
    AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
      if (isAnyPrioritizedThreadBlocked()) {
        checkLaterThreadsAreUnblocked();
      }
      else {
        restorePrioritizing();
      }
    }, 5, TimeUnit.MILLISECONDS);
  }
  catch (RejectedExecutionException ignore) {
  }
}
 
Example #23
Source File: PerformanceWatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public PerformanceWatcher(ContainerPathManager containerPathManager) {
  myContainerPathManager = containerPathManager;
  myCurHangLogDir = mySessionLogDir = new File(ContainerPathManager.get().getLogPath() + "/threadDumps-" + myDateFormat.format(new Date()) + "-" + ApplicationInfo.getInstance().getBuild().asString());
  myPublisher = ApplicationManager.getApplication().getMessageBus().syncPublisher(IdePerformanceListener.TOPIC);
  myThread = JobScheduler.getScheduler().scheduleWithFixedDelay((Runnable)() -> samplePerformance(), SAMPLING_INTERVAL_MS, SAMPLING_INTERVAL_MS, TimeUnit.MILLISECONDS);

  UNRESPONSIVE_THRESHOLD_SECONDS = SystemProperties.getIntProperty("performance.watcher.threshold", 5);
  UNRESPONSIVE_INTERVAL_SECONDS = SystemProperties.getIntProperty("performance.watcher.interval", 5);

  if (shouldWatch()) {
    final AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService();
    service.setNewThreadListener(new Consumer<Thread>() {
      private final int ourReasonableThreadPoolSize = Registry.intValue("core.pooled.threads");

      @Override
      public void consume(Thread thread) {
        if (service.getBackendPoolExecutorSize() > ourReasonableThreadPoolSize && ApplicationProperties.isInSandbox()) {
          File file = dumpThreads("newPooledThread/", true);
          LOG.info("Not enough pooled threads" + (file != null ? "; dumped threads into file '" + file.getPath() + "'" : ""));
        }
      }
    });

    ApplicationManager.getApplication().executeOnPooledThread((Runnable)() -> deleteOldThreadDumps());

    for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) {
      if ("Code Cache".equals(bean.getName())) {
        watchCodeCache(bean);
        break;
      }
    }
  }
}
 
Example #24
Source File: RootUIBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void scheduleWelcomeFrame(UIAccess access, Window window) {
  AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
    WebApplication application = WebApplication.getInstance();
    if (application == null || !((ApplicationEx)application).isLoaded()) {
      if (access.isValid()) {
        scheduleWelcomeFrame(access, window);
      }
      return;
    }

    if (access.isValid()) {
      access.give(() -> showWelcomeFrame(application, window));
    }
  }, 1, TimeUnit.SECONDS);
}
 
Example #25
Source File: WebContainerStartup.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void startApplication(@Nonnull StatCollector stat, @Nonnull String[] args) {
  Runnable appInitializeMark = stat.mark(StatCollector.APP_INITIALIZE);

  StartupUtil.prepareAndStart(args, WebImportantFolderLocker::new, (newConfigFolder, commandLineArgs) -> {
    ApplicationStarter app = new ApplicationStarter(WebPostStarter.class, commandLineArgs);

    AppExecutorUtil.getAppExecutorService().execute(() -> {
      PluginManager.installExceptionHandler();
      app.run(stat, appInitializeMark, newConfigFolder);
    });
  });
}
 
Example #26
Source File: Alarm.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Alarm(@Nonnull ThreadToUse threadToUse, @Nullable Disposable parentDisposable) {
  myThreadToUse = threadToUse;

  myExecutorService = threadToUse == ThreadToUse.SWING_THREAD ?
                      // pass straight to EDT
                      EdtExecutorService.getScheduledExecutorInstance() :

                      // or pass to app pooled thread.
                      // have to restrict the number of running tasks because otherwise the (implicit) contract of
                      // "addRequests with the same delay are executed in order" will be broken
                      AppExecutorUtil.createBoundedScheduledExecutorService("Alarm Pool", 1);

  if (parentDisposable == null) {
    if (threadToUse != ThreadToUse.SWING_THREAD) {
      boolean crash = threadToUse == ThreadToUse.POOLED_THREAD || ApplicationManager.getApplication().isUnitTestMode();
      IllegalArgumentException t = new IllegalArgumentException("You must provide parent Disposable for non-swing thread Alarm");
      if (crash) {
        throw t;
      }
      // do not crash yet in case of deprecated SHARED_THREAD
      LOG.warn(t);
    }
  }
  else {
    Disposer.register(parentDisposable, this);
  }
}
 
Example #27
Source File: ShardedTargetList.java    From intellij with Apache License 2.0 5 votes vote down vote up
private BuildResult runInParallel(
    Project project,
    BlazeContext context,
    Function<List<TargetExpression>, BuildResult> invocation) {
  // new executor for each sync, so we get an up-to-date experiment value. This is fine, because
  // it's just a view of the single application pool executor. Doesn't need to be shutdown for the
  // same reason
  ListeningExecutorService executor =
      MoreExecutors.listeningDecorator(
          AppExecutorUtil.createBoundedApplicationPoolExecutor(
              "RemoteBlazeExecutor", remoteConcurrentSyncs.getValue()));

  ListenableFuture<List<BuildResult>> future =
      Futures.allAsList(
          shardedTargets.stream()
              .map(s -> executor.submit(() -> invocation.apply(s)))
              .collect(toImmutableList()));

  String buildSystem = Blaze.buildSystemName(project);
  List<BuildResult> results =
      FutureUtil.waitForFuture(context, future)
          .onError(String.format("%s build failed", buildSystem))
          .run()
          .result();
  if (results == null) {
    return BuildResult.FATAL_ERROR;
  }
  return results.stream().reduce(BuildResult::combine).orElse(BuildResult.FATAL_ERROR);
}
 
Example #28
Source File: SkylarkDebugProcess.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void scheduleWakeupIfNecessary(int delayMillis) {
  if (pausedThreads.size() < 2) {
    // if no other threads are paused, the UI state will already be up-to-date
    return;
  }
  @SuppressWarnings({"unused", "nullness"})
  Future<?> possiblyIgnoredError =
      AppExecutorUtil.getAppScheduledExecutorService()
          .schedule(this::wakeUpUiIfNecessary, delayMillis, TimeUnit.MILLISECONDS);
}
 
Example #29
Source File: Unity3dProjectChangeListener.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private void checkAndRunIfNeed(UIAccess uiAccess)
{
	myUpdateCheckTask.cancel(false);
	myUpdateCheckTask = CompletableFuture.completedFuture(null);

	myActive.set(Unity3dModuleExtensionUtil.getRootModuleExtension(myProject) != null);

	if(!myActive.get())
	{
		return;
	}

	myUpdateCheckTask = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay((Runnable) this::checkNotification, 10, 10, TimeUnit.SECONDS);
}
 
Example #30
Source File: ModuleDataService.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void importData(@Nonnull final Collection<DataNode<ModuleData>> toImport, @Nonnull final Project project, final boolean synchronous) {
  if (toImport.isEmpty()) {
    return;
  }
  if (!project.isInitialized()) {
    myFuture = AppExecutorUtil.getAppScheduledExecutorService()
            .schedule(new ImportModulesTask(project, toImport, synchronous), PROJECT_INITIALISATION_DELAY_MS, TimeUnit.MILLISECONDS);
    return;
  }
  ExternalSystemApiUtil.executeProjectChangeAction(synchronous, new DisposeAwareProjectChange(project) {
    @RequiredUIAccess
    @Override
    public void execute() {
      final Collection<DataNode<ModuleData>> toCreate = filterExistingModules(toImport, project);
      if (!toCreate.isEmpty()) {
        createModules(toCreate, project);
      }
      for (DataNode<ModuleData> node : toImport) {
        Module module = ProjectStructureHelper.findIdeModule(node.getData(), project);
        if (module != null) {
          syncPaths(module, node.getData());
        }
      }
    }
  });
}