summaryrefslogtreecommitdiffstats
path: root/jrt/src/com/yahoo/jrt/Connector.java
blob: 61143e8a78bfa6d0dfddadbe480bffe3c3153f7f (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import com.yahoo.concurrent.ThreadFactoryFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;

class Connector {

    private final Transport   parent;
    private final ExecutorService executor = Executors.newCachedThreadPool(ThreadFactoryFactory.getDaemonThreadFactory("jrt.connector"));
    private boolean     done = false;

    private void connect(Connection conn) {
        try {
            conn.transportThread().addConnection(conn.connect());
        } catch (Throwable problem) {
            parent.handleFailure(problem, Connector.this);
        }
    }

    public Connector(Transport parent) {
        this.parent = parent;
    }

    public void connectLater(Connection conn) {
        try {
            executor.execute(() -> connect(conn));
        } catch (RejectedExecutionException e) {
            conn.transportThread().addConnection(conn);
        }

    }

    public Connector shutdown() {
        executor.shutdown();
        join();
        synchronized (this) {
            done = true;
            notifyAll();
        }
        return this;
    }

    public synchronized void waitDone() {
        while (!done) {
            try { wait(); } catch (InterruptedException x) {}
        }
    }

    public synchronized Connector exit() {
        notifyAll();
        return this;
    }

    public void join() {
        while (true) {
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
                return;
            } catch (InterruptedException e) {}
        }
    }
}