aboutsummaryrefslogtreecommitdiffstats
path: root/service-monitor/src/test/java/com/yahoo/vespa/service/executor/TestRunlet.java
blob: 40d055514e01907295fe0b53b5c35fd3a0aadfcf (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.executor;

/**
 * @author hakonhall
 */
public class TestRunlet implements Runlet {
    private final Object monitor = new Object();
    private boolean running = false;
    private boolean shouldWaitInRun = false;
    private boolean closed = false;
    private int runsStarted = 0;
    private int runsCompleted = 0;

    int getRunsStarted() {
        synchronized (monitor) {
            return runsStarted;
        }
    }

    int getRunsCompleted() {
        return runsCompleted;
    }

    boolean isClosed() {
        synchronized (monitor) {
            return closed;
        }
    }

    void shouldWaitInRun(boolean value) {
        synchronized (monitor) {
            shouldWaitInRun = value;
            monitor.notifyAll();
        }
    }

    void waitUntilInRun() {
        synchronized (monitor) {
            while (!running) {
                uncheckedWait();
            }
        }
    }

    void waitUntilCompleted(int runsCompleted) {
        synchronized (monitor) {
            while (this.runsCompleted < runsCompleted) {
                uncheckedWait();
            }
        }
    }

    void waitUntilClosed() {
        synchronized (monitor) {
            while (!closed) {
                uncheckedWait();
            }
        }
    }

    @Override
    public void run() {
        synchronized (monitor) {
            if (closed) {
                throw new IllegalStateException("run after close");
            }

            ++runsStarted;
            running = true;
            monitor.notifyAll();

            while (shouldWaitInRun) {
                uncheckedWait();
            }

            ++runsCompleted;
            running = false;
            monitor.notifyAll();
        }
    }

    @Override
    public void close() {
        synchronized (monitor) {
            closed = true;
            monitor.notifyAll();
        }
    }

    private void uncheckedWait() {
        try {
            monitor.wait();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}