Alachisoft.NCache.Common.Threading.ThrottlingManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nc-common Show documentation
Show all versions of nc-common Show documentation
Internal package of Alachisoft.
package Alachisoft.NCache.Common.Threading;
// Copyright (c) 2020 Alachisoft
//
// 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
import com.alachisoft.ncache.runtime.util.TimeSpan;
import java.util.Date;
public class ThrottlingManager {
private long _limit;
private long _throtllingUnitMs = 1000;
private long _currentInternval;
private long _currentSize;
private long _currentMilliSeconds;
private Date _startTime;
public ThrottlingManager(long limit) {
_limit = limit;
}
public ThrottlingManager(long limit, long unit) {
_limit = limit;
_throtllingUnitMs = unit;
}
public final void start() {
_startTime = new Date();
_currentMilliSeconds = getMilliSecondDiff();
_currentInternval = _currentMilliSeconds / _throtllingUnitMs;
}
private long getMilliSecondDiff() {
return TimeSpan.subtract(new Date(), _startTime).getTotalMiliSeconds();
}
/**
* Waits if throttling limit reaches
*
* @param size
*/
public final void throttle(long size) {
try {
synchronized (this) {
long msNow = getMilliSecondDiff();
long currentInterval = msNow / _throtllingUnitMs;
if (currentInterval == _currentInternval) {
_currentSize += size;
if (_currentSize >= _limit) {
Thread.sleep((int) (_throtllingUnitMs - (msNow - _currentMilliSeconds)));
}
} else {
_currentInternval = currentInterval;
_currentMilliSeconds = msNow;
_currentSize = size;
}
}
} catch (InterruptedException e) {
}
}
}