/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.kylin.common.util;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.val;

//https://www.baeldung.com/java-executor-wait-for-threads
public class ExecutorServiceUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceUtil.class);

    public static void shutdownGracefully(ExecutorService threadPool, int timeoutSeconds) {
        threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
                forceShutdown(threadPool);
            }
        } catch (InterruptedException ex) {
            logger.info("Interrupted while shutting down");
            forceShutdown(threadPool);
            Thread.currentThread().interrupt();
        }
    }

    public static void forceShutdown(ExecutorService threadPool) {
        if (threadPool != null) {
            List<Runnable> jobs = threadPool.shutdownNow();
            logger.info("Shutdown now thread pool [{}], drain [{}] runnable jobs.", System.identityHashCode(threadPool),
                    jobs.size());
            int futureTaskCount = 0;
            for (Runnable job : jobs) {
                if (job instanceof Future) {
                    futureTaskCount++;
                    val task = (Future) job;
                    logger.info("Cancel future task [{}].", System.identityHashCode(task));
                    task.cancel(true);
                }
            }
            logger.info("Thread poll cancel [{}] future jobs.", futureTaskCount);
        }
    }
}
