aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/concurrent/CachedThreadPoolWithFallback.java
blob: c693d46975f0e177495c7e361e42b79c93e67bac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 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 thread pool before falling back to an unbounded
 * single threaded thread pool 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 keepAliveTime, TimeUnit timeUnit) {
        primary = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, 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) {}
        }
    }

}