1 /*******************************************************************************
2 * ============LICENSE_START==================================================
4 * * ===========================================================================
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * * ===========================================================================
7 * * Licensed under the Apache License, Version 2.0 (the "License");
8 * * you may not use this file except in compliance with the License.
9 * * You may obtain a copy of the License at
11 * * http://www.apache.org/licenses/LICENSE-2.0
13 * * Unless required by applicable law or agreed to in writing, software
14 * * distributed under the License is distributed on an "AS IS" BASIS,
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * * See the License for the specific language governing permissions and
17 * * limitations under the License.
18 * * ============LICENSE_END====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.node;
27 import java.util.Timer;
28 import java.util.TimerTask;
31 * Execute an operation no more frequently than a specified interval.
34 public abstract class RateLimitedOperation implements Runnable {
36 private boolean marked; // a timer task exists
37 private boolean executing; // the operation is currently in progress
38 private boolean remark; // a request was made while the operation was in progress
40 private long last; // when the last operation started
41 private long mininterval;
44 * Create a rate limited operation.
46 * @param mininterval The minimum number of milliseconds after the last execution starts before a new execution can
48 * @param timer The timer used to perform deferred executions
50 public RateLimitedOperation(long mininterval, Timer timer) {
52 this.mininterval = mininterval;
56 * Request that the operation be performed by this thread or at a later time by the timer.
58 public void request() {
68 private synchronized boolean premark() {
70 // currently executing - wait until it finishes
75 // timer currently running - will run when it expires
78 long now = System.currentTimeMillis();
79 if (last + mininterval > now) {
80 // too soon - schedule a timer
82 timer.schedule(new Deferred(), last + mininterval - now);
91 private synchronized boolean demark() {
100 private class Deferred extends TimerTask {
106 private void execute() {
111 private synchronized void unmark() {