在看LeapArray.currentWindow这个方法之前,先来看一个短小简单但是足够核心的一个方法LeapArray.calculateTimeIdx,整个方法只有两行代码,如下:
private int calculateTimeIdx(long timeMillis) {
// 将传入的当前时间按照窗口时长进行分段,拿到当前时间对应的分段ID
long timeId = timeMillis / windowLengthInMs;
// 将当前时间的分段段ID对应到窗口数组的下标ID上
return (int)(timeId % array.length());
}
上面的array定义如下:
protected final AtomicReferenceArray> array;
其赋值在构造方法中,如下语句:
this.array = new AtomicReferenceArray<>(sampleCount);
通过上面这个方法,我们就能够得到当前时间对应的窗口在窗口数组中的位置了,接下来我们要做的事情就是根据这个位置取出对应的窗口返回去给对应的统计逻辑使用。
直接看LeapArray.currentWindow[^为了方便阅读,精简了它的注释]方法定义:
public WindowWrap currentWindow(long timeMillis) {
if (timeMillis < 0) {
return null;
}
// 获取当前时间在窗口数组中映射的下标
int idx = calculateTimeIdx(timeMillis);
// 计算当前时间对应的窗口的开始时间,具体方法见下面
long windowStart = calculateWindowStart(timeMillis);
/*
* Get bucket item at given time from the array.
*
* (1) Bucket is absent, then just create a new bucket and CAS update to circular array.
* (2) Bucket is up-to-date, then just return the bucket.
* (3) Bucket is deprecated, then reset current bucket and clean all deprecated buckets.
*/
while (true) {
WindowWrap old = array.get(idx);
if (old == null) {
// 第一次进入,新建窗口,并使用cas的方式设置,如果出现争抢导致设置失败,暂时让出执行权待其它线程成功设置
WindowWrap window = new WindowWrap(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));
if (array.compareAndSet(idx, null, window)) {
return window;
} else {
Thread.yield();
}
} else if (windowStart == old.windowStart()) {
// 当前时间对应的窗口开始时间等于获取到的窗口开始时间,那么当前获取到的窗口就是我们需要的
