// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler.threadpool;

import com.google.common.util.concurrent.ForwardingExecutorService;
import com.yahoo.container.protect.ProcessTerminator;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A service executor wrapper which emits metrics and
 * shuts down the vm when no workers are available for too long to avoid containers lingering in a blocked state.
 * Package private for testing
 *
 * @author Steinar Knutsen
 * @author baldersheim
 * @author bratseth
 */
class ExecutorServiceWrapper extends ForwardingExecutorService {

    private final WorkerCompletionTimingThreadPoolExecutor wrapped;
    private final ThreadPoolMetric metric;
    private final ProcessTerminator processTerminator;
    private final long maxThreadExecutionTimeMillis;
    private final Thread metricReporter;
    private final AtomicBoolean closed = new AtomicBoolean(false);

    ExecutorServiceWrapper(
            WorkerCompletionTimingThreadPoolExecutor wrapped,
            ThreadPoolMetric metric, ProcessTerminator processTerminator,
            long maxThreadExecutionTimeMillis) {
        this.wrapped = wrapped;
        this.metric = metric;
        this.processTerminator = processTerminator;
        this.maxThreadExecutionTimeMillis = maxThreadExecutionTimeMillis;

        metric.reportThreadPoolSize(wrapped.getPoolSize());
        metric.reportActiveThreads(wrapped.getActiveCount());
        metricReporter = new Thread(this::reportMetrics);
        metricReporter.setDaemon(true);
        metricReporter.start();
    }

    int queuedTasks() { return wrapped.getQueue().size(); }

    private final void reportMetrics() {
        try {
            while (!closed.get()) {
                metric.reportThreadPoolSize(wrapped.getPoolSize());
                metric.reportActiveThreads(wrapped.getActiveCount());
                Thread.sleep(100);
            }
        } catch (InterruptedException e) { }
    }

    @Override
    public void shutdown() {
        super.shutdown();
        closed.set(true);
    }

    /**
     * Tracks all instances of {@link RejectedExecutionException}.
     * {@link ContainerThreadPool} returns an executor, so external uses will not
     * have access to the methods declared by {@link ExecutorService}.
     * ({@link Executor#execute(Runnable)} is declared by {@link Executor}.)
     */
    @Override
    public void execute(Runnable command) {
        try {
            super.execute(command);
        } catch (RejectedExecutionException e) {
            metric.reportRejectRequest();
            long timeSinceLastReturnedThreadMillis = System.currentTimeMillis() - wrapped.lastThreadAssignmentTimeMillis;
            if (timeSinceLastReturnedThreadMillis > maxThreadExecutionTimeMillis)
                processTerminator.logAndDie("No worker threads have been available for " +
                        timeSinceLastReturnedThreadMillis + " ms. Shutting down.", true);
            throw e;
        }
    }

    @Override
    protected ExecutorService delegate() { return wrapped; }

}


@@ -1351,16 +1351,29 @@
 meMillis
+, String name
 ) %7B%0A    
@@ -1737,16 +1737,86 @@
 trics);%0A
+        metricReporter.setName(name + %22-threadpool-metric-reporter%22);%0A
         
@@ -1959,22 +1959,16 @@
 private 
-final 
 void rep

Set name of metric reporter thread