Java 类com.intellij.util.concurrency.AppExecutorUtil 实例源码

项目:consulo-unity3d    文件:UnityPlayerService.java   
@Override
public void initComponent()
{
    myUpdateFuture = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay((Runnable) () ->
    {
        for(Iterator<Map.Entry<UnityPlayer, UnityPlayer>> iterator = myPlayers.entrySet().iterator(); iterator.hasNext(); )
        {
            Map.Entry<UnityPlayer, UnityPlayer> next = iterator.next();

            if(!next.getKey().isAvailable())
            {
                iterator.remove();
            }
        }
    }, 5, 5, TimeUnit.SECONDS);

    AppExecutorUtil.getAppExecutorService().execute(this::bind);
}
项目:consulo    文件:WebPostStarter.java   
@Override
public void main(boolean newConfigFolder, @Nonnull CommandLineArgs args) {
  StartupProgress startupProgress = mySplashRef.get();
  if (startupProgress != null) {
    startupProgress.dispose();
    mySplashRef.set(null);
  }

  AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(() -> {
    System.out.println("Save All");

    Application application = ApplicationManager.getApplication();
    if(application == null || application.isDisposed()) {
      return;
    }

    SwingUtilities.invokeLater(() -> application.saveSettings());
  }, 1, 5, TimeUnit.MINUTES);
}
项目:consulo    文件:WebLoader.java   
public void start(String[] args) {
  File home = new File(args[0]);

  System.setProperty("java.awt.headless", "true");
  System.setProperty(PathManager.PROPERTY_HOME_PATH, home.getPath());
  System.setProperty(PathManager.PROPERTY_CONFIG_PATH, home.getPath() + "/.config/sandbox/config");
  System.setProperty(PathManager.PROPERTY_SYSTEM_PATH, home.getPath() + "/.config/sandbox/system");
  System.setProperty(ApplicationProperties.CONSULO_PLUGINS_PATHS, new File(home, "plugins").getPath());

  Main.setFlags(new String[0]);

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

    AppExecutorUtil.getAppExecutorService().execute(() -> {
      PluginManager.installExceptionHandler();
      app.run(newConfigFolder);
    });
  });
}
项目:consulo    文件:ProgressManagerImpl.java   
public ProgressManagerImpl() {
  HeavyProcessLatch.INSTANCE.addUIActivityListener(new HeavyProcessLatch.HeavyProcessListener() {
    private final CheckCanceledHook sleepHook = indicator -> sleepIfNeededToGivePriorityToAnotherThread();
    private final AtomicBoolean scheduled = new AtomicBoolean();
    private final Runnable addHookLater = () -> {
      scheduled.set(false);
      if (HeavyProcessLatch.INSTANCE.hasPrioritizedThread()) {
        addCheckCanceledHook(sleepHook);
      }
    };

    @Override
    public void processStarted() {
      if (scheduled.compareAndSet(false, true)) {
        AppExecutorUtil.getAppScheduledExecutorService().schedule(addHookLater, 5, TimeUnit.MILLISECONDS);
      }
    }

    @Override
    public void processFinished() {
      removeCheckCanceledHook(sleepHook);
    }

  }, this);
}
项目:consulo    文件:IdeEventQueue.java   
boolean doPostEvent(@Nonnull AWTEvent event) {
  for (PostEventHook listener : myPostEventListeners.getListeners()) {
    if (listener.consumePostedEvent(event)) return false;
  }

  String message = myFrequentEventDetector.getMessageOnEvent(event);
  if (message != null) {
    // we can't log right here, because logging has locks inside, and postEvents can deadlock if it's blocked by anything (IDEA-161322)
    AppExecutorUtil.getAppExecutorService().submit(() -> myFrequentEventDetector.logMessage(message));
  }

  if (isKeyboardEvent(event)) {
    myKeyboardEventsPosted.incrementAndGet();
  }

  if (isFocusEvent(event)) {
    focusEventsList.add(event);
  }

  super.postEvent(event);
  return true;
}
项目:consulo-unity3d    文件:Unity3dProjectChangeListener.java   
@RequiredReadAction
private void checkAndRunIfNeed()
{
    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);
}
项目:consulo-unity3d    文件:UnityProcessDialog.java   
@Override
public void show()
{
    myTask = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay((Runnable) () -> UIUtil.invokeLaterIfNeeded(() ->
    {
        List<UnityProcess> selectedElements = myChooser.getSelectedElements();
        UnityProcessDialog.this.setElements(collectItems(), selectedElements);
    }), 0, 1, TimeUnit.SECONDS);
    super.show();
}
项目:consulo-apache-ant    文件:AntIntrospector.java   
private static void scheduleCacheCleaning()
{
    ourCacheCleaner.cancel(false);
    ourCacheCleaner = AppExecutorUtil.getAppScheduledExecutorService().schedule((Runnable) () ->
    {
        synchronized(ourCache)
        {
            ourCache.clear();
        }
    }, CACHE_CLEAN_TIMEOUT, TimeUnit.SECONDS);
}
项目:consulo    文件:RootUIBuilder.java   
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);
}
项目:consulo    文件:Alarm.java   
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.POOLED_THREAD || 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);
  }
}
项目:consulo    文件:ModuleDataService.java   
@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) {
    @RequiredDispatchThread
    @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());
        }
      }
    }
  });
}
项目:consulo    文件:ModuleDataService.java   
@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);
}
项目:consulo    文件:RemoteExternalSystemFacadeImpl.java   
/**
 * 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);
}
项目:consulo    文件:ApplicationImpl.java   
@Override
public void dispose() {
  fireApplicationExiting();

  ShutDownTracker.getInstance().ensureStopperThreadsFinished();

  disposeComponents();

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

  super.dispose();
  Disposer.dispose(myLastDisposable); // dispose it last
}
项目:consulo    文件:SmoothProgressAdapter.java   
@Override
public synchronized void start() {
  if (isRunning()) return;

  super.start();
  myOriginalStarted = false;
  myStartupAlarm = AppExecutorUtil.getAppScheduledExecutorService().schedule(myShowRequest, SHOW_DELAY, TimeUnit.MILLISECONDS);
}
项目:consulo    文件:ProjectUtil.java   
@Nonnull
public static AsyncResult<Project> openAsync(@Nonnull String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame, @Nonnull UIAccess uiAccess) {
  final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);

  if (virtualFile == null) return AsyncResult.rejected("file path not find");

  AsyncResult<Project> result = new AsyncResult<>();

  ProjectOpenProcessor provider = ProjectOpenProcessors.getInstance().findProcessor(VfsUtilCore.virtualToIoFile(virtualFile));
  if (provider != null) {
    AppExecutorUtil.getAppExecutorService().execute(() -> {
      result.doWhenDone((project) -> {
        uiAccess.give(() -> {
          if (!project.isDisposed()) {
            final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);
            if (toolWindow != null) {
              toolWindow.activate(null);
            }
          }
        });
      });

      ApplicationManager.getApplication().runInWriteThreadAndWait(() -> provider.doOpenProjectAsync(result, virtualFile, projectToClose, forceOpenInNewFrame, uiAccess));
    });

    return result;
  }
  return AsyncResult.rejected("provider for file path is not find");
}
项目:consulo    文件:PerformanceWatcher.java   
@Override
public void initComponent() {
  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(new Runnable() {
      @Override
      public void run() {
        deleteOldThreadDumps();
      }
    });

    for (MemoryPoolMXBean bean : ManagementFactory.getMemoryPoolMXBeans()) {
      if ("Code Cache".equals(bean.getName())) {
        watchCodeCache(bean);
        break;
      }
    }
  }
}
项目:consulo-java    文件:DebuggerManagerThreadImpl.java   
/**
 * waits COMMAND_TIMEOUT milliseconds
 * if worker thread is still processing the same command
 * calls terminateCommand
 */
public void terminateAndInvoke(DebuggerCommandImpl command, int terminateTimeoutMillis)
{
    final DebuggerCommandImpl currentCommand = myEvents.getCurrentEvent();

    invoke(command);

    if(currentCommand != null)
    {
        AppExecutorUtil.getAppScheduledExecutorService().schedule(() ->
        {
            if(currentCommand == myEvents.getCurrentEvent())
            {
                // if current command is still in progress, cancel it
                getCurrentRequest().requestStop();
                try
                {
                    getCurrentRequest().join();
                }
                catch(InterruptedException ignored)
                {
                }
                catch(Exception e)
                {
                    throw new RuntimeException(e);
                }
                finally
                {
                    if(!myDisposed)
                    {
                        startNewWorkerThread();
                    }
                }
            }
        }, terminateTimeoutMillis, TimeUnit.MILLISECONDS);
    }
}
项目:consulo-unity3d    文件:Unity3dConsoleManager.java   
@Inject
public Unity3dConsoleManager(Application application)
{
    myProcessingTask = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(this::pop, 2, 2, TimeUnit.SECONDS);
    application.getMessageBus().connect().subscribe(UnityLogHandler.TOPIC, myMessages::add);
}
项目:consulo    文件:AnimatedLogoLabel.java   
public void start() {
  if (myAnimated) {
    myFuture = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(myTask, 50, 20, TimeUnit.MILLISECONDS);
  }
}
项目:consulo    文件:ApplicationImpl.java   
public ApplicationImpl(boolean isHeadless, @Nonnull Ref<? extends StartupProgress> splashRef) {
  super(null);

  ApplicationManager.setApplication(this, myLastDisposable); // reset back to null only when all components already disposed

  getPicoContainer().registerComponentInstance(Application.class, this);

  getPicoContainer().registerComponentInstance(TransactionGuard.class.getName(), myTransactionGuard);

  AWTExceptionHandler.register(); // do not crash AWT on exceptions

  myIsInternal = ApplicationProperties.isInternal();

  String debugDisposer = System.getProperty("idea.disposer.debug");
  Disposer.setDebugMode((myIsInternal || "on".equals(debugDisposer)) && !"off".equals(debugDisposer));

  myStartTime = System.currentTimeMillis();
  mySplashRef = splashRef;

  boolean isUnitTestMode = false;

  myTestModeFlag = isUnitTestMode;
  myHeadlessMode = isHeadless;
  myCommandLineMode = isUnitTestMode;

  myDoNotSave = isUnitTestMode || isHeadless;
  gatherStatistics = LOG.isDebugEnabled() || isUnitTestMode() || isInternal();

  loadApplicationComponents();

  if (myTestModeFlag) {
    registerShutdownHook();
  }

  if (!isUnitTestMode && !isHeadless) {
    Disposer.register(this, Disposer.newDisposable(), "ui");

    StartupUtil.addExternalInstanceListener(commandLineArgs -> {
      LOG.info("ApplicationImpl.externalInstanceListener invocation");
      final Project project = CommandLineProcessor.processExternalCommandLine(commandLineArgs, null);
      final IdeFrame frame = WindowManager.getInstance().getIdeFrame(project);

      if (frame != null) AppIcon.getInstance().requestFocus(frame);
    });

    WindowsCommandLineProcessor.LISTENER = (currentDirectory, commandLine) -> {
      LOG.info("Received external Windows command line: current directory " + currentDirectory + ", command line " + commandLine);
      invokeLater(() -> {
        final List<String> args = StringUtil.splitHonorQuotes(commandLine, ' ');
        args.remove(0);   // process name
        CommandLineProcessor.processExternalCommandLine(CommandLineArgs.parse(ArrayUtil.toStringArray(args)), currentDirectory);
      });
    };
  }

  Thread edt = UIUtil.invokeAndWaitIfNeeded(() -> {
    // instantiate AppDelayQueue which starts "Periodic task thread" which we'll mark busy to prevent this EDT to die
    // that thread was chosen because we know for sure it's running
    AppScheduledExecutorService service = (AppScheduledExecutorService)AppExecutorUtil.getAppScheduledExecutorService();
    Thread thread = service.getPeriodicTasksThread();
    AWTAutoShutdown.getInstance().notifyThreadBusy(thread); // needed for EDT not to exit suddenly
    Disposer.register(this, () -> {
      AWTAutoShutdown.getInstance().notifyThreadFree(thread); // allow for EDT to exit - needed for Upsource
    });
    return Thread.currentThread();
  });
  myLock = new ReadMostlyRWLock(edt);

  if (isUnitTestMode) {
    ApplicationStarter.ourLoaded = true;
  }

  NoSwingUnderWriteAction.watchForEvents(this);
}
项目:consulo    文件:UpdateCheckerComponent.java   
private void queueNextUpdateCheck(long interval) {
  myCheckFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(myCheckRunnable, interval, TimeUnit.MILLISECONDS);
}
项目:consulo    文件:BaseRemoteProcessHandler.java   
@Nonnull
private static Future<?> executeOnPooledThread(@Nonnull Runnable task) {
  return AppExecutorUtil.getAppExecutorService().submit(task);
}
项目:consulo    文件:BaseOSProcessHandler.java   
/** @deprecated use {@link BaseOSProcessHandler#executeTask(Runnable)} instead (to be removed in IDEA 17) */
public static Future<?> submit(@Nonnull Runnable task) {
  LOG.warn("Deprecated method. Please use com.intellij.execution.process.BaseOSProcessHandler.executeTask() instead", new Throwable());
  return AppExecutorUtil.getAppExecutorService().submit(task);
}
项目:consulo    文件:EnvironmentUtil.java   
@Nonnull
@Override
protected Future<?> executeOnPooledThread(@Nonnull Runnable runnable) {
  return AppExecutorUtil.getAppExecutorService().submit(runnable);
}
项目:consulo    文件:ScopeEditorPanel.java   
private void rebuild(final boolean updateText, @Nullable final Runnable runnable, final boolean requestFocus, final int delayMillis){
  myUpdateAlarm.cancel(false);
  final Runnable request = new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        @Override
        public void run() {
          if (updateText) {
            final String text = myCurrentScope != null ? myCurrentScope.getText() : null;
            SwingUtilities.invokeLater(new Runnable() {
              @Override
              public void run() {
                try {
                  myIsInUpdate = true;
                  myPatternField.setText(text);
                }
                finally {
                  myIsInUpdate = false;
                }
              }
            });
          }

          try {
            if (!myProject.isDisposed()) {
              updateTreeModel(requestFocus);
            }
          }
          catch (ProcessCanceledException e) {
            return;
          }
          if (runnable != null) {
            runnable.run();
          }
        }
      });
    }
  };
  myUpdateAlarm = AppExecutorUtil.getAppScheduledExecutorService().schedule(request, delayMillis, TimeUnit.MILLISECONDS);
}
项目:consulo    文件:ExternalStorageQueue.java   
void wantLoad(@Nonnull String fileSpec, @Nonnull RoamingType roamingType, int mod, @Nonnull StateStorageManager stateStorageManager) {
  myLoadTask.cancel(false);

  myLoadItems.add(new LoadItem(fileSpec, roamingType, mod, stateStorageManager));

  myLoadTask = AppExecutorUtil.getAppScheduledExecutorService().schedule(this::executeLoad, 1, TimeUnit.MINUTES);
}