summaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/search/dispatch/CloseableInvoker.java
blob: 9da89c6bfd852ad6a5e260667bef6e40531df2a5 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch;

import java.io.Closeable;
import java.time.Duration;
import java.util.function.BiConsumer;

/**
 * CloseableInvoker is an abstract implementation of {@link Closeable} with an additional hook for
 * executing code at closing. Classes that extend CloseableInvoker need to override {@link #release()}
 * instead of {@link #close()} which is final to avoid accidental overriding.
 *
 * @author ollivir
 */
public abstract class CloseableInvoker implements Closeable {

    protected abstract void release();

    private BiConsumer<Boolean, Duration> teardown = null;
    private boolean success = false;
    private long startTime = 0;

    public void teardown(BiConsumer<Boolean, Duration> teardown) {
        this.teardown = teardown;
        this.startTime = System.nanoTime();
    }

    protected void setFinalStatus(boolean success) {
        this.success = success;
    }

    @Override
    public final void close() {
        if (teardown != null) {
            teardown.accept(success, Duration.ofNanos(System.nanoTime() - startTime));
            teardown = null;
        }
        release();
    }

}