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

import java.util.ArrayList;
import java.util.List;

import com.yahoo.statistics.SampleSet.Sampling;

/**
 * Book-keeping class to know which SampleSet instances have unlogged data.
 *
 * @author <a href="mailto:steinar@yahoo-inc.com">Steinar Knutsen</a>
 */
final class SampleDirectory {
    private final Object directoryLock = new Object();
    private List<SampleSet> directory = new ArrayList<>(200);

    void put(SampleSet s) {
        synchronized (directoryLock) {
            directory.add(s);
            s.setRegisteredForLogging(true);
        }
    }

    /**
     * Get a view of the current generation of data and instantiate a new
     * generation. This does the memory barrier two-step for the
     * client.
     */
    Sampling[] fetchValues() {
        Sampling[] copyToReturn;
        synchronized (directoryLock) {
            List<SampleSet> tmpDir = directory;
            copyToReturn = new Sampling[tmpDir.size()];
            List<SampleSet> newDir = new ArrayList<>(200);
            for (int i = 0; i < copyToReturn.length; ++i) {
                copyToReturn[i] = tmpDir.get(i).getAndReset();
            }
            directory = newDir;
        }
        return copyToReturn;
    }

    /**
     * Return a view of the current generation of data. This does the memory
     * barrier two-step for the client.
     */
    Sampling[] viewValues() {
        Sampling[] copy;
        synchronized (directoryLock) {
            copy = new Sampling[directory.size()];
            for (int i = 0; i < copy.length; ++i) {
                copy[i] = directory.get(i).values;
            }
        }
        return copy;
    }

}