Java Code Examples for java.util.concurrent.ExecutorService#isShutdown()

The following examples show how to use java.util.concurrent.ExecutorService#isShutdown() . 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: TaskExecutor.java    From NIM_Android_UIKit with MIT License 6 votes vote down vote up
public void shutdown() {
    ExecutorService executor = null;

    synchronized (this) {
        // swap
        if (service != null) {
            executor = service;
            service = null;
        }
    }

    if (executor != null) {
        // shutdown
        if (!executor.isShutdown()) {
            executor.shutdown();
        }

        // recycle
        executor = null;
    }
}
 
Example 2
Source File: Close.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 关闭线程池
 *
 * @param executor 线程池
 * @param timeout  超时时间(毫秒)
 */
public static Close close(final ExecutorService executor, final long timeout) {
    if (executor != null && !executor.isShutdown()) {
        if (timeout <= 0) {
            executor.shutdownNow();
        } else {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(timeout, TimeUnit.MILLISECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException ignored) {
            }
        }
    }
    return instance;
}
 
Example 3
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * That method starts a set of threads, each thread sends a given number of
 * notifications.
 * The number of threads can be set via the attribute numOfNotificationSenders.
 * The number of notification sent by each thread can be set via
 * the attribute numOfNotificationSenderLoops.
 * Depending on the parameter customNotification we send either custom
 * notification(s) or MBeanServer registration and unregistration notification(s).
 * When customNotification=true the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops). They are
 * sequentially of type NOTIF_TYPE_0 then NOTIF_TYPE_1 and so on.
 *
 * When customNotification=false the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops) registration
 * notification(s)
 * +
 * (numOfNotificationSenders * numOfNotificationSenderLoops) unregistration
 * notification(s)
 *
 * @throws java.lang.Exception
 */
public void sendNotificationWave(boolean customNotification) throws
        Exception {
    // Build the set of notification sender.
    Collection<Callable<Integer>> tasks =
            new HashSet<Callable<Integer>>(numOfNotificationSenders);

    for (int i = 1; i <= numOfNotificationSenders; i++) {
        tasks.add(new NotifSender(numOfNotificationSenderLoops,
                customNotification, i));
    }

    // Start all notification sender in parallel.
    ExecutorService execServ = null;
    try {
        execServ = Executors.newFixedThreadPool(numOfNotificationSenders);
        List<Future<Integer>> taskHandlers = execServ.invokeAll(tasks);
        checkNotifSenderThreadStatus(taskHandlers);
    } finally {
        if (!execServ.isShutdown()) {
            execServ.shutdown();
        }
    }
}
 
Example 4
Source File: Basic.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * That method starts a set of threads, each thread sends a given number of
 * notifications.
 * The number of threads can be set via the attribute numOfNotificationSenders.
 * The number of notification sent by each thread can be set via
 * the attribute numOfNotificationSenderLoops.
 * Depending on the parameter customNotification we send either custom
 * notification(s) or MBeanServer registration and unregistration notification(s).
 * When customNotification=true the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops). They are
 * sequentially of type NOTIF_TYPE_0 then NOTIF_TYPE_1 and so on.
 *
 * When customNotification=false the total number of notification(s) sent is
 * (numOfNotificationSenders * numOfNotificationSenderLoops) registration
 * notification(s)
 * +
 * (numOfNotificationSenders * numOfNotificationSenderLoops) unregistration
 * notification(s)
 *
 * @throws java.lang.Exception
 */
public void sendNotificationWave(boolean customNotification) throws
        Exception {
    // Build the set of notification sender.
    Collection<Callable<Integer>> tasks =
            new HashSet<Callable<Integer>>(numOfNotificationSenders);

    for (int i = 1; i <= numOfNotificationSenders; i++) {
        tasks.add(new NotifSender(numOfNotificationSenderLoops,
                customNotification, i));
    }

    // Start all notification sender in parallel.
    ExecutorService execServ = null;
    try {
        execServ = Executors.newFixedThreadPool(numOfNotificationSenders);
        List<Future<Integer>> taskHandlers = execServ.invokeAll(tasks);
        checkNotifSenderThreadStatus(taskHandlers);
    } finally {
        if (!execServ.isShutdown()) {
            execServ.shutdown();
        }
    }
}
 
Example 5
Source File: ExecutorServiceHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Call shutdown on the {@link ExecutorService} and wait indefinitely until it
 * terminated.
 *
 * @param aES
 *        The {@link ExecutorService} to operate on. May not be
 *        <code>null</code>.
 * @param nTimeout
 *        the maximum time to wait. Must be &gt; 0.
 * @param eUnit
 *        the time unit of the timeout argument. Must not be <code>null</code>
 *        .
 * @return {@link EInterrupt#INTERRUPTED} if the executor service was
 *         interrupted while awaiting termination. Never <code>null</code>.
 */
@Nonnull
public static EInterrupt shutdownAndWaitUntilAllTasksAreFinished (@Nonnull final ExecutorService aES,
                                                                  @Nonnegative final long nTimeout,
                                                                  @Nonnull final TimeUnit eUnit)
{
  ValueEnforcer.notNull (aES, "ExecutorService");

  if (aES.isShutdown ())
    return EInterrupt.NOT_INTERRUPTED;

  // accept no further requests
  aES.shutdown ();

  // Wait...
  return waitUntilAllTasksAreFinished (aES, nTimeout, eUnit);
}
 
Example 6
Source File: Threads.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 停止线程池
 * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
 * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
 * 如果仍人超時,則強制退出.
 * 另对在shutdown时线程本身被调用中断做了处理.
 */
public static void shutdownAndAwaitTermination(ExecutorService pool)
{
    if (pool != null && !pool.isShutdown())
    {
        pool.shutdown();
        try
        {
            if (!pool.awaitTermination(120, TimeUnit.SECONDS))
            {
                pool.shutdownNow();
                if (!pool.awaitTermination(120, TimeUnit.SECONDS))
                {
                    logger.info("Pool did not terminate");
                }
            }
        }
        catch (InterruptedException ie)
        {
            pool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
 
Example 7
Source File: MessageOnlyChannelHandler.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public void received(Channel channel, Object message) throws RemotingException {
    ExecutorService cexecutor = executor;
    if (cexecutor == null || cexecutor.isShutdown()) {
        cexecutor = SHARED_EXECUTOR;
    }
    try {
        cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
    } catch (Throwable t) {
        throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
    }
}
 
Example 8
Source File: AllChannelHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private ExecutorService getExecutorService() {
    ExecutorService cexecutor = executor;
    if (cexecutor == null || cexecutor.isShutdown()) { 
        cexecutor = SHARED_EXECUTOR;
    }
    return cexecutor;
}
 
Example 9
Source File: Simulation.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start the simulation instance.
 */
public void startSimThread(boolean useDefaultName) {
	// Start the simulation.
	ExecutorService e = getSimExecutor();
	if (e == null || (e != null && (e.isTerminated() || e.isShutdown())))
		startSimExecutor();
	e.submit(new StartTask(useDefaultName));
}
 
Example 10
Source File: ConnectionOrderedChannelHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void received(Channel channel, Object message) throws RemotingException {
    ExecutorService cexecutor = executor;
    if (cexecutor == null || cexecutor.isShutdown()) {
        cexecutor = SHARED_EXECUTOR;
    }
    try {
        cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
    } catch (Throwable t) {
        throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
    }
}
 
Example 11
Source File: ConnectorScheduler.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
private synchronized void shutdownExecutor(ExecutorService executor) {
  if ((executor == null) || executor.isShutdown()) {
    return;
  }
  executor.shutdown();
  try {
    executor.awaitTermination(10L, TimeUnit.SECONDS);
  } catch (InterruptedException ex) {
    logger.log(Level.WARNING, "Interrupted during executor termination.", ex);
    Thread.currentThread().interrupt();
  }
  executor.shutdownNow();
}
 
Example 12
Source File: StartMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void shutdownExecutorService(ExecutorService executorService) {
    if (!executorService.isShutdown()) {
        executorService.shutdown();
        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.warn("ExecutorService did not shutdown normally.");
            executorService.shutdownNow();
        }
    }
}
 
Example 13
Source File: ConnectionOrderedChannelHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void caught(Channel channel, Throwable exception) throws RemotingException {
    ExecutorService cexecutor = executor;
    if (cexecutor == null || cexecutor.isShutdown()) { 
        cexecutor = SHARED_EXECUTOR;
    } 
    try{
        cexecutor.execute(new ChannelEventRunnable(channel, handler ,ChannelState.CAUGHT, exception));
    }catch (Throwable t) {
        throw new ExecutionException("caught event", channel, getClass()+" error when process caught event ." , t);
    }
}
 
Example 14
Source File: MarsProject.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start the simulation instance.
 */
public void startConsoleThread() {
	// Start the simulation.
	ExecutorService e = sim.getSimExecutor();
	if (e == null || (e != null && (e.isTerminated() || e.isShutdown())))
		sim.startSimExecutor();
	e.submit(new ConsoleTask());
}
 
Example 15
Source File: ConnectionOrderedChannelHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void caught(Channel channel, Throwable exception) throws RemotingException {
    ExecutorService cexecutor = executor;
    if (cexecutor == null || cexecutor.isShutdown()) { 
        cexecutor = SHARED_EXECUTOR;
    } 
    try{
        cexecutor.execute(new ChannelEventRunnable(channel, handler ,ChannelState.CAUGHT, exception));
    }catch (Throwable t) {
        throw new ExecutionException("caught event", channel, getClass()+" error when process caught event ." , t);
    }
}
 
Example 16
Source File: SyntaxHighlightingCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Task<StyleSpans<Collection<String>>> computeHighlightingAsync(ExecutorService service, SyntaxHighlighter highlighter, String text) {
    Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {
        @Override
        protected StyleSpans<Collection<String>> call() {
            return highlighter.computeHighlighting(text);
        }
    };
    if (!service.isShutdown()) {
        service.execute(task);
    }
    return task;
}
 
Example 17
Source File: TDataSource.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public ExecutorService borrowExecutorService() {
    if (globalExecutorService != null) {
        return globalExecutorService;
    } else {
        ExecutorService executor = executorServiceQueue.poll();
        if (executor == null) {
            Object poolSizeObj = GeneralUtil.getExtraCmdString(this.getConnectionProperties(),
                ConnectionProperties.CONCURRENT_THREAD_SIZE);
            int poolSize = 0;
            if (poolSizeObj != null) {
                poolSize = Integer.valueOf(poolSizeObj.toString());
            } else {
                poolSize = TddlConstants.DEFAULT_CONCURRENT_THREAD_SIZE;
            }

            if (activeCount.addAndGet(poolSize) <= maxActive) {
                executor = createThreadPool(poolSize, false);
            } else {
                executor = createThreadPool(poolSize, true);
            }
        }

        if (executor.isShutdown()) {
            return borrowExecutorService();
        } else {
            return executor;
        }
    }
}
 
Example 18
Source File: EmbeddedEnvironmentFactory.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored") // no need to monitor shutdown thread
public RemoteEnvironment createEnvironment(Environment environment, String workerId)
    throws Exception {
  ExecutorService executor = Executors.newSingleThreadExecutor();
  Future<?> fnHarness =
      executor.submit(
          () -> {
            try {
              FnHarness.main(
                  workerId,
                  options,
                  loggingServer.getApiServiceDescriptor(),
                  controlServer.getApiServiceDescriptor(),
                  InProcessManagedChannelFactory.create(),
                  OutboundObserverFactory.clientDirect());
            } catch (NoClassDefFoundError e) {
              // TODO: https://issues.apache.org/jira/browse/BEAM-4384 load the FnHarness in a
              // Restricted classpath that we control for any user.
              LOG.error(
                  "{} while executing an in-process FnHarness. "
                      + "To use the {}, "
                      + "the 'org.apache.beam:beam-sdks-java-harness' artifact "
                      + "and its dependencies must be on the classpath",
                  NoClassDefFoundError.class.getSimpleName(),
                  EmbeddedEnvironmentFactory.class.getSimpleName(),
                  e);
              throw e;
            }
            return null;
          });
  executor.submit(
      () -> {
        try {
          fnHarness.get();
        } catch (Throwable t) {
          executor.shutdownNow();
        }
      });

  InstructionRequestHandler handler = null;
  // Wait on a client from the gRPC server.
  while (handler == null) {
    try {
      // If the thread is not alive anymore, we abort.
      if (executor.isShutdown()) {
        throw new IllegalStateException("FnHarness startup failed");
      }
      // TODO: find some way to populate the actual ID in FnHarness.main()
      handler = clientSource.take("", Duration.ofSeconds(5L));
    } catch (TimeoutException timeoutEx) {
      LOG.info("Still waiting for startup of FnHarness");
    } catch (InterruptedException interruptEx) {
      Thread.currentThread().interrupt();
      throw new RuntimeException(interruptEx);
    }
  }
  return RemoteEnvironment.forHandler(environment, handler);
}
 
Example 19
Source File: RestartableExecutorServiceTest.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Test
void all_calls_delegates() throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService delegate = mock(ExecutorService.class);
    ExecutorService executorService = new RestartableExecutorService(() -> delegate);

    executorService.shutdown();
    verify(delegate, atLeastOnce()).shutdown();

    executorService.shutdownNow();
    verify(delegate, atLeastOnce()).shutdownNow();

    executorService.isShutdown();
    verify(delegate, atLeastOnce()).isShutdown();

    executorService.isTerminated();
    verify(delegate, atLeastOnce()).isTerminated();

    executorService.awaitTermination(3L, TimeUnit.SECONDS);
    verify(delegate, atLeastOnce()).awaitTermination(3L, TimeUnit.SECONDS);

    executorService.submit(mock(Callable.class));
    verify(delegate, atLeastOnce()).submit(any(Callable.class));

    executorService.submit(mock(Runnable.class), new Object());
    verify(delegate, atLeastOnce()).submit(any(Runnable.class), any());

    executorService.submit(mock(Runnable.class));
    verify(delegate, atLeastOnce()).submit(any(Runnable.class));

    executorService.invokeAll(Collections.<Callable<Object>>singletonList(mock(Callable.class)));
    verify(delegate, atLeastOnce()).invokeAll(any());

    executorService.invokeAll(Collections.<Callable<Object>>singletonList(mock(Callable.class)), 7L, TimeUnit.MILLISECONDS);
    verify(delegate, atLeastOnce()).invokeAll(any(), eq(7L), eq(TimeUnit.MILLISECONDS));

    executorService.invokeAny(Collections.<Callable<Object>>singletonList(mock(Callable.class)));
    verify(delegate, atLeastOnce()).invokeAny(any());

    executorService.invokeAny(Collections.<Callable<Object>>singletonList(mock(Callable.class)), 7L, TimeUnit.MILLISECONDS);
    verify(delegate, atLeastOnce()).invokeAny(any(), eq(7L), eq(TimeUnit.MILLISECONDS));

    executorService.execute(mock(Runnable.class));
    verify(delegate, atLeastOnce()).execute(any());
}
 
Example 20
Source File: ExecutorUtils.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
/**
 * 停掉线程池
 *
 * @param executorService
 */
public static void shutdown(ExecutorService executorService) {
    if (!executorService.isShutdown()) {
        executorService.shutdown();
    }
}