ExecutorService 优雅关闭线程

/*
 * Copyright 2018 LinkedIn Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package azkaban.utils;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Executor service related utilities.
 */
public class ExecutorServiceUtils {

  private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceUtils.class);
  private static final TimeUnit MILLI_SECONDS_TIME_UNIT = TimeUnit.MILLISECONDS;

  /**
   * Gracefully shuts down the given executor service.
   *
   * <p>Adopted from
   * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html">
   * the Oracle JAVA Documentation.
   * </a>
   *
   * @param service the service to shutdown
   * @param timeout max wait time for the tasks to shutdown. Note that the max wait time is 2
   *     times this value due to the two stages shutdown strategy.
   * @throws InterruptedException if the current thread is interrupted
   */
  public void gracefulShutdown(final ExecutorService service, final Duration timeout)
      throws InterruptedException {
    service.shutdown(); // Disable new tasks from being submitted禁止提交新任务
    final long timeout_in_unit_of_miliseconds = timeout.toMillis();
    // Wait a while for existing tasks to terminate现有任务需要一段时间才能终止
    if (!service.awaitTermination(timeout_in_unit_of_miliseconds, MILLI_SECONDS_TIME_UNIT)) {
      service.shutdownNow(); // Cancel currently executing tasks  
      // 取消当前正在执行的任务
     
      // Wait a while for tasks to respond to being cancelled等待任务响应被取消
      if (!service.awaitTermination(timeout_in_unit_of_miliseconds, MILLI_SECONDS_TIME_UNIT)) {
        logger.error("The executor service did not terminate.");
      }
    }
  }
}

shutdown方法:平滑的关闭ExecutorService,当此方法被调用时,ExecutorService停止接收新的任务并且等待已经提交的任务(包含提交正在执行和提交未执行)执行完成。当所有提交任务执行完毕,线程池即被关闭。

awaitTermination方法:接收人timeout和TimeUnit两个参数,用于设定超时时间及单位。当等待超过设定时间时,会监测ExecutorService是否已经关闭,若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。

   3.shutdownNow方法的作用是向所有执行中的线程发出interrupted以中止线程的运行。这时,各个线程会抛出               InterruptedException异常(前提是
线程中运行了sleep等会抛出异常的方法)

在上述代码中 shutdown方法的意思是等待当前正在执行的线程执行完毕 并且停止接受新的线程执行,如果新开线程的话会抛出RejectedExecutionException异常

awaitTermination的第一个参数是时间,第二个参数是时间单位,在这个地方监视线程是否都执行完毕,如果执行完毕后会执行后面的代码

 

一般情况下awaitTermination和shutdown配合使用,在上述代码中如果注释掉shutdown方法则awaitTermination不会监视到线程池关闭的信息 所以在这个地方代码会堵塞,

如果注释掉awaitTermination方法 则后面的代码不会得到线程执行过的结果
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值