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