aboutsummaryrefslogtreecommitdiffstats
path: root/jrt/src/com/yahoo/jrt/Connector.java
blob: 4c83a2884bd5523a7fd303e657ec15e688a285cf (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
69
70
71
72
73
74
75
76
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;


class Connector {

    private class Run implements Runnable {
        public void run() {
            try {
                Connector.this.run();
            } catch (Throwable problem) {
                parent.handleFailure(problem, Connector.this);
            }
        }
    }

    private Thread      thread = new Thread(new Run(), "<jrt-connector>");
    private Transport   parent;
    private ThreadQueue connectQueue = new ThreadQueue();
    private boolean     done = false;
    private boolean     exit = false;

    public Connector(Transport parent) {
        this.parent = parent;
        thread.setDaemon(true);
        thread.start();
    }

    public void connectLater(Connection c) {
        if ( ! connectQueue.enqueue(c)) {
            c.transportThread().addConnection(c);
        }
    }

    private void run() {
        try {
            while (true) {
                Connection conn = (Connection) connectQueue.dequeue();
                conn.transportThread().addConnection(conn.connect());
            }
        } catch (EndOfQueueException e) {}
        synchronized (this) {
            done = true;
            notifyAll();
            while (!exit) {
                try { wait(); } catch (InterruptedException x) {}
            }
        }
    }

    public Connector shutdown() {
        connectQueue.close();
        return this;
    }

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

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

    public void join() {
        while (true) {
            try {
                thread.join();
                return;
            } catch (InterruptedException e) {}
        }
    }
}