// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package com.yahoo.concurrent;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * An executor that will first try a bounded cached threadpool before falling back to a unbounded
 * single threaded threadpool that will take over dispatching to the primary pool.
 *
 */
public class CachedThreadPoolWithFallback implements AutoCloseable, Executor {
    private final ExecutorService primary;
    private final ExecutorService secondary;
    public CachedThreadPoolWithFallback(String baseName, int corePoolSize, int maximumPoolSize, long keepAlimeTime, TimeUnit timeUnit) {
        primary = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAlimeTime, timeUnit,
                new SynchronousQueue<>(), ThreadFactoryFactory.getDaemonThreadFactory(baseName + ".primary"));
        secondary = Executors.newSingleThreadExecutor(ThreadFactoryFactory.getDaemonThreadFactory(baseName + ".secondary"));
    }
    @Override
    public void execute(Runnable command) {
        try {
            primary.execute(command);
        } catch (RejectedExecutionException e1) {
            secondary.execute(() -> retryForever(command));
        }
    }
    private void retryForever(Runnable command) {
        while (true) {
            try {
                primary.execute(command);
                return;
            } catch (RejectedExecutionException rejected) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException silenced) { }
            }
        }
    }

    @Override
    public void close() {
        secondary.shutdown();
        join(secondary);
        primary.shutdown();
        join(primary);
    }
    private static void join(ExecutorService executor) {
        while (true) {
            try {
                if (executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    return;
                }
            } catch (InterruptedException e) {}
        }
    }
}

@@ -499,24 +499,25 @@
 ached thread
+ 
 pool before 
@@ -533,16 +533,17 @@
 ack to a
+n
  unbound
@@ -570,16 +570,17 @@
 d thread
+ 
 pool tha
@@ -799,24 +799,25 @@
  secondary;%0A
+%0A
     public C
@@ -908,25 +908,25 @@
 long keepAli
-m
+v
 eTime, TimeU
@@ -1020,17 +1020,17 @@
  keepAli
-m
+v
 eTime, t
@@ -1276,24 +1276,25 @@
 y%22));%0A    %7D%0A
+%0A
     @Overrid
@@ -1513,24 +1513,25 @@
     %7D%0A    %7D%0A
+%0A
     private 
@@ -2033,24 +2033,25 @@
 ary);%0A    %7D%0A
+%0A
     private 
@@ -2311,16 +2311,17 @@
       %7D%0A
-
     %7D%0A
+%0A
 %7D%0A

Fix variable name, minor javadoc and formatting changes