Window.java 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright 2017, OpenSkywalking Organization All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Project repository: https://github.com/OpenSkywalking/skywalking
 */

P
pengys5 已提交
19
package org.skywalking.apm.collector.stream.worker.impl.data;
20

P
pengys5 已提交
21 22
import java.util.concurrent.atomic.AtomicInteger;

23 24 25 26 27
/**
 * @author pengys5
 */
public abstract class Window {

P
pengys5 已提交
28 29
    private AtomicInteger windowSwitch = new AtomicInteger(0);

30 31 32 33 34 35 36 37 38 39 40
    private DataCollection pointer;

    private DataCollection windowDataA;
    private DataCollection windowDataB;

    public Window() {
        windowDataA = new DataCollection();
        windowDataB = new DataCollection();
        pointer = windowDataA;
    }

P
pengys5 已提交
41
    public boolean trySwitchPointer() {
P
pengys5 已提交
42
        return windowSwitch.incrementAndGet() == 1 && !getLast().isReading();
P
pengys5 已提交
43 44
    }

P
pengys5 已提交
45 46 47 48
    public void trySwitchPointerFinally() {
        windowSwitch.addAndGet(-1);
    }

49 50 51 52 53 54
    public void switchPointer() {
        if (pointer == windowDataA) {
            pointer = windowDataB;
        } else {
            pointer = windowDataA;
        }
P
pengys5 已提交
55
        getLast().reading();
56 57
    }

P
pengys5 已提交
58
    protected DataCollection getCurrentAndWriting() {
59
        if (pointer == windowDataA) {
P
pengys5 已提交
60
            windowDataA.writing();
61 62
            return windowDataA;
        } else {
P
pengys5 已提交
63
            windowDataB.writing();
64 65 66 67
            return windowDataB;
        }
    }

P
pengys5 已提交
68 69 70 71
    protected DataCollection getCurrent() {
        return pointer;
    }

72 73 74 75 76 77 78
    public DataCollection getLast() {
        if (pointer == windowDataA) {
            return windowDataB;
        } else {
            return windowDataA;
        }
    }
P
pengys5 已提交
79

P
pengys5 已提交
80
    public void finishReadingLast() {
P
pengys5 已提交
81
        getLast().clear();
P
pengys5 已提交
82
        getLast().finishReading();
P
pengys5 已提交
83
    }
84
}