aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerTermination.java
blob: 4c7c26358d6949f242a423984b83b1f23d3cb017 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;

import com.yahoo.jdisc.application.DeactivatedContainer;

/**
 * @author Simon Thoresen Hult
 */
public class ContainerTermination implements DeactivatedContainer, Runnable {

    private final Object lock = new Object();
    private final Object appContext;
    private Runnable task;
    private boolean done;

    public ContainerTermination(Object appContext) {
        this.appContext = appContext;
    }

    @Override
    public Object appContext() {
        return appContext;
    }

    @Override
    public void notifyTermination(Runnable task) {
        boolean done;
        synchronized (lock) {
            if (this.task != null) {
                throw new IllegalStateException();
            }
            this.task = task;
            done = this.done;
        }
        if (done) {
            task.run();
        }
    }

    @Override
    public void run() {
        Runnable task;
        synchronized (lock) {
            done = true;
            task = this.task;
        }
        if (task != null) {
            task.run();
        }
    }
}