Пример #1
1
  public void runReadAction(@NotNull final Runnable action) {
    /**
     * if we are inside read action, do not try to acquire read lock again since it will deadlock if
     * there is a pending writeAction see {@link
     * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()}
     */
    if (isReadAccessAllowed()) {
      action.run();
      return;
    }

    LOG.assertTrue(
        !Thread.holdsLock(PsiLock.LOCK),
        "Thread must not hold PsiLock while performing readAction");
    try {
      myActionsLock.readLock().acquire();
    } catch (InterruptedException e) {
      throw new RuntimeInterruptedException(e);
    }

    try {
      action.run();
    } finally {
      myActionsLock.readLock().release();
    }
  }
Пример #2
1
  public boolean tryRunReadAction(@NotNull Runnable action) {
    /**
     * if we are inside read action, do not try to acquire read lock again since it will deadlock if
     * there is a pending writeAction see {@link
     * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()}
     */
    boolean mustAcquire = !isReadAccessAllowed();

    if (mustAcquire) {
      LOG.assertTrue(
          myTestModeFlag || !Thread.holdsLock(PsiLock.LOCK),
          "Thread must not hold PsiLock while performing readAction");
      try {
        if (!myActionsLock.readLock().attempt(0)) return false;
      } catch (InterruptedException e) {
        throw new RuntimeInterruptedException(e);
      }
    }

    try {
      action.run();
    } finally {
      if (mustAcquire) {
        myActionsLock.readLock().release();
      }
    }
    return true;
  }
Пример #3
0
 @Override
 public void run() {
   try {
     runnable.run();
   } catch (Exception e) {
     logger.warn("failed to run {}", e, runnable.toString());
   }
 }
 public void runWriteAction(@NotNull final Runnable action) {
   final AccessToken token = acquireWriteActionLock(action.getClass());
   try {
     action.run();
   } finally {
     token.finish();
   }
 }
Пример #5
0
  public <T> T getCurrentWriteAction(@Nullable Class<T> actionClass) {
    assertCanRunWriteAction();

    for (int i = myWriteActionsStack.size() - 1; i >= 0; i--) {
      Runnable action = myWriteActionsStack.get(i);
      if (actionClass == null || ReflectionCache.isAssignable(actionClass, action.getClass()))
        return (T) action;
    }
    return null;
  }
Пример #6
0
 @Override
 public void run() {
   while (true) {
     try {
       Runnable task = queue.take();
       task.run();
     } catch (InterruptedException e) {
       break; /* Allow thread to exit */
     }
   }
 }
Пример #7
0
  public void dispatch() {
    while (true) {
      Runnable methodRequest;
      try {
        methodRequest = activationQueue.take();

        // 防止个别任务执行失败导致线程终止的代码在run方法中
        methodRequest.run();
      } catch (InterruptedException e) {
        // 处理该异常
      }
    }
  }
Пример #8
0
 @Override
 public void run() {
   while (running) {
     try {
       Runnable task = tasks.poll(timeout, MILLISECONDS);
       heartbeat();
       if (task == null) continue;
       task.run();
     } catch (Throwable t) {
       running = onInterruptedBy(t);
     }
   }
 }
Пример #9
0
 @SuppressWarnings("InfiniteLoopStatement")
 @Override
 public void run() {
   while (true) {
     Runnable task = Uninterruptibles.takeUninterruptibly(tasks);
     try {
       task.run();
     } catch (Throwable throwable) {
       log.warn("Exception in user thread", throwable);
       Thread.UncaughtExceptionHandler handler = uncaughtExceptionHandler;
       if (handler != null) handler.uncaughtException(this, throwable);
     }
   }
 }
Пример #10
0
 /**
  * Creates a new debug scope that is unrelated to the current scope and runs a given task in the
  * new scope.
  *
  * @param name new scope name
  * @param context the context objects of the new scope
  * @param config the debug configuration to use for the new scope
  * @param runnable the task to run in the new scope
  */
 public static void sandbox(String name, Object[] context, DebugConfig config, Runnable runnable) {
   if (ENABLED) {
     DebugScope.getInstance().scope(name, runnable, null, true, config, context);
   } else {
     runnable.run();
   }
 }
Пример #11
0
 public static void scope(String name, Object[] context, Runnable runnable) {
   if (ENABLED) {
     DebugScope.getInstance().scope(name, runnable, null, false, null, context);
   } else {
     runnable.run();
   }
 }
 public void run() {
   try {
     runnable.run();
   } catch (Throwable e) {
     DebuggableThreadPoolExecutor.handleOrLog(e);
   }
 }
  public void runReadAction(@NotNull final Runnable action) {
    final AccessToken token = acquireReadActionLockImpl(false);

    try {
      action.run();
    } finally {
      token.finish();
    }
  }
Пример #14
0
  /** simply dump status info to the textarea */
  private void sout(final String s) {
    Runnable soutRunner =
        new Runnable() {
          public void run() {
            if (ttaStatus.getText().equals("")) {
              ttaStatus.setText(s);
            } else {
              ttaStatus.setText(ttaStatus.getText() + "\n" + s);
            }
          }
        };

    if (ThreadUtils.isInEDT()) {
      soutRunner.run();
    } else {
      SwingUtilities.invokeLater(soutRunner);
    }
  }
    public void executeQueuedRunnables() {
      long millis = System.currentTimeMillis();
      int count = 1;

      Runnable runnable = queue.peek();
      while (runnable != null && shouldResume(count, millis)) {
        log.trace("Executing runnable #{}", count);
        try {
          runnable.run();
        } catch (Throwable e) {
          log.error("Could not execute runnable #{}", count, e);
        } finally {
          queue.poll();
          count++;
        }
        runnable = queue.peek();
      }
    }
Пример #16
0
  public void exit(final boolean force) {
    if (!force && getDefaultModalityState() != ModalityState.NON_MODAL) {
      return;
    }

    Runnable runnable =
        new Runnable() {
          public void run() {
            if (!force) {
              if (!showConfirmation()) {
                saveAll();
                myExitCode = 0;
                return;
              }
            }

            getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).appClosing();

            FileDocumentManager.getInstance().saveAllDocuments();

            saveSettings();

            if (!canExit()) {
              myExitCode = 0;
              return;
            }

            final boolean success = disposeSelf();
            if (!success || isUnitTestMode()) {
              myExitCode = 0;
              return;
            }

            System.exit(myExitCode);
          }
        };

    if (!isDispatchThread()) {
      invokeLater(runnable, ModalityState.NON_MODAL);
    } else {
      runnable.run();
    }
  }
Пример #17
0
 public void run() {
   if (isDone()) return;
   try {
     task.run();
   } catch (Throwable t) {
     log.error(Util.getMessage("FailedExecutingTask") + task, t);
   } finally {
     done = true;
   }
 }
 @Override
 public void execute(Runnable command) {
   checkNotShutdown();
   if (isCurrentThread()) {
     command.run();
   } else {
     queue.add(command);
     triggerQueueReading();
   }
 }
Пример #19
0
 public void run() {
   if (isDone()) return;
   try {
     task.run();
   } catch (Throwable t) {
     log.error("failed executing task " + task, t);
   } finally {
     done = true;
   }
 }
Пример #20
0
 public void run() {
   ticktock();
   try {
     ticktock();
     _work.run();
     ticktock();
   } catch (Throwable ex) {
     ticktock();
     __log.fatal("Internal Error", ex);
   }
 }
Пример #21
0
 /**
  * oneway调用,只发送请求,不接收返回结果.
  *
  * @param callable
  */
 public void asyncCall(Runnable runable) {
   try {
     setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString());
     runable.run();
   } catch (Throwable e) {
     // FIXME 异常是否应该放在future中?
     throw new RpcException("oneway call error ." + e.getMessage(), e);
   } finally {
     removeAttachment(Constants.RETURN_KEY);
   }
 }
Пример #22
0
  public void runWriteAction(@NotNull final Runnable action) {
    assertCanRunWriteAction();

    ActivityTracker.getInstance().inc();
    fireBeforeWriteActionStart(action);
    final AtomicBoolean stopped = new AtomicBoolean(false);

    if (ourDumpThreadsOnLongWriteActionWaiting > 0) {
      executeOnPooledThread(
          new Runnable() {
            @Override
            public void run() {
              while (!stopped.get()) {
                try {
                  Thread.sleep(ourDumpThreadsOnLongWriteActionWaiting);
                  if (!stopped.get()) {
                    PerformanceWatcher.getInstance().dumpThreads(true);
                  }
                } catch (InterruptedException ignored) {
                }
              }
            }
          });
    }

    LOG.assertTrue(
        myActionsLock.isWriteLockAcquired(Thread.currentThread())
            || !Thread.holdsLock(PsiLock.LOCK),
        "Thread must not hold PsiLock while performing writeAction");
    try {
      myActionsLock.writeLock().acquire();
    } catch (InterruptedException e) {
      throw new RuntimeInterruptedException(e);
    }
    stopped.set(true);

    try {
      myWriteActionsStack.push(action);

      fireWriteActionStarted(action);

      action.run();
    } finally {
      try {
        fireWriteActionFinished(action);

        myWriteActionsStack.pop();
      } finally {
        myActionsLock.writeLock().release();
      }
    }
  }
Пример #23
0
    public void run() {
      if (cancelled) {
        if (future != null) future.cancel(true);
        return;
      }

      try {
        task.run();
      } catch (Throwable t) {
        log.error("failed running task " + task, t);
      }
      if (!cancelled) doSchedule();
    }
Пример #24
0
    public void run() {
      if (cancelled) {
        if (future != null) future.cancel(true);
        return;
      }

      try {
        task.run();
      } catch (Throwable t) {
        log.error(Util.getMessage("FailedRunningTask") + task, t);
      }
      if (!cancelled) doSchedule();
    }
  // if {@code things} are too few to be processed in the real pool, returns TRUE if processed
  // successfully, FALSE if not
  // returns null if things need to be processed in the real pool
  private static <T> Boolean processImmediatelyIfTooFew(
      @NotNull final List<T> things,
      @NotNull final ProgressIndicator progress,
      boolean runInReadAction,
      @NotNull final Processor<? super T> thingProcessor) {
    // commit can be invoked from within write action
    // if (runInReadAction && ApplicationManager.getApplication().isWriteAccessAllowed()) {
    //  throw new RuntimeException("Must not run invokeConcurrentlyUnderProgress() from under write
    // action because of imminent deadlock");
    // }
    if (things.isEmpty()) return true;

    if (things.size() <= 1 || JobSchedulerImpl.CORES_COUNT <= CORES_FORK_THRESHOLD) {
      final AtomicBoolean result = new AtomicBoolean(true);
      Runnable runnable =
          () ->
              ProgressManager.getInstance()
                  .executeProcessUnderProgress(
                      () -> {
                        //noinspection ForLoopReplaceableByForEach
                        for (int i = 0; i < things.size(); i++) {
                          T thing = things.get(i);
                          if (!thingProcessor.process(thing)) {
                            result.set(false);
                            break;
                          }
                        }
                      },
                      progress);
      if (runInReadAction) {
        if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(runnable)) return false;
      } else {
        runnable.run();
      }
      return result.get();
    }
    return null;
  }
Пример #26
0
  public void runEdtSafeAction(@NotNull Runnable runnable) {
    Integer value = ourEdtSafe.get();
    if (value == null) {
      value = Integer.valueOf(0);
    }

    ourEdtSafe.set(value + 1);

    try {
      runnable.run();
    } finally {
      int newValue = ourEdtSafe.get() - 1;
      ourEdtSafe.set(newValue >= 1 ? newValue : null);
    }
  }
 @Override
 protected boolean exec() {
   myStatus = Status.STARTED;
   try {
     myAction.run();
     complete(null); // complete manually before calling callback
   } catch (Throwable throwable) {
     completeExceptionally(throwable);
   } finally {
     myStatus = Status.EXECUTED;
     if (myOnDoneCallback != null) {
       myOnDoneCallback.consume(this);
     }
   }
   return true;
 }
Пример #28
0
  public void invokeAndWait(@NotNull Runnable runnable, @NotNull ModalityState modalityState) {
    if (isDispatchThread()) {
      LOG.error("invokeAndWait must not be called from event queue thread");
      runnable.run();
      return;
    }

    if (isExceptionalThreadWithReadAccess()) { // OK if we're in exceptional thread.
      LaterInvocator.invokeAndWait(runnable, modalityState);
      return;
    }

    if (myActionsLock.isReadLockAcquired()) {
      LOG.error("Calling invokeAndWait from read-action leads to possible deadlock.");
    }

    LaterInvocator.invokeAndWait(runnable, modalityState);
  }
Пример #29
0
  @Override
  public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    if (r instanceof RunnableScheduledFuture) {
      Object callable = ReflectionUtil.getFieldValue(r, "callable");
      Object cfAsync = ReflectionUtil.getFieldValue(callable, "task");
      r = (Runnable) cfAsync;
    }

    if (r instanceof ForkJoinTask && r.toString().contains("CompletableFuture$Async")) {
      Field field = ReflectionUtil.getField(r, "dst"); // jdk8u20
      if (field == null) {
        field = ReflectionUtil.getField(r, "dep"); // jdk8u40
      }
      Object dst = ReflectionUtil.getFieldValue(r, field);
      if (dst instanceof CompletableFuture) {
        ((CompletableFuture) dst).cancel(false);
        log.debug("Canceled completable future {}", r);
      }
    } else if (r instanceof Future) {
      ((Future) r).cancel(false);
      log.debug("Canceled future {}", r);
    }
  }
 @Override
 public void run() {
   AppContext appContext = AppContext.getInstance();
   try {
     barrier.await();
   } catch (InterruptedException | BrokenBarrierException e) {
     e.printStackTrace();
     Thread.currentThread().interrupt();
   }
   for (int i = 0; i < AppContext.getInstance().getGeneratedItemCountPerConnection(); i++) {
     if (hangingSimulator != null) {
       hangingSimulator.run();
     }
     lastTime += ThreadLocalRandom.current().nextInt(100);
     BigDecimal amount = new BigDecimal(ThreadLocalRandom.current().nextInt(100));
     Item item = new Item(lastTime, amount);
     itemConsumer.accept(item);
     appContext.getClientRegistry().registerLastClientTime(id, lastTime);
     appContext.addToTotalGeneratedAmount(amount);
   }
   appContext.getClientRegistry().deregisterClient(id);
   System.out.println(MessageFormat.format("Client id {0} exited successfully.", id));
   System.out.println("appContext = " + appContext.getWorkQueue().size());
 }