2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.tesla.internal.throttler;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.Iterator;
19 import java.util.concurrent.ScheduledExecutorService;
22 * The {@link AbstractMultiRateChannelThrottler} is abstract class implementing
23 * a throttler with multiple global execution rates, or rate limiters
25 * @author Karel Goderis - Initial contribution
27 abstract class AbstractMultiRateChannelThrottler implements ChannelThrottler {
29 protected final TimeProvider timeProvider;
30 protected final ScheduledExecutorService scheduler;
31 protected final Map<Object, Rate> channels = new HashMap<>();
32 protected final ArrayList<Rate> rates = new ArrayList<>();
34 protected AbstractMultiRateChannelThrottler(Rate rate, ScheduledExecutorService scheduler,
35 Map<Object, Rate> channels, TimeProvider timeProvider) {
37 this.scheduler = scheduler;
38 this.channels.putAll(channels);
39 this.timeProvider = timeProvider;
42 public synchronized void addRate(Rate rate) {
46 protected synchronized long callTime(Rate channel) {
48 long finalCallTime = 0;
49 long now = timeProvider.getCurrentTimeInMillis();
50 Iterator<Rate> iterator = rates.iterator();
51 while (iterator.hasNext()) {
52 Rate someRate = iterator.next();
53 maxCallTime = Math.max(maxCallTime, someRate.callTime(now));
56 if (channel != null) {
57 finalCallTime = Math.max(maxCallTime, channel.callTime(now));
58 channel.addCall(finalCallTime);
61 iterator = rates.iterator();
62 while (iterator.hasNext()) {
63 Rate someRate = iterator.next();
64 someRate.addCall(finalCallTime);
70 protected long getThrottleDelay(Object channelKey) {
71 long delay = callTime(channels.get(channelKey)) - timeProvider.getCurrentTimeInMillis();
72 return delay < 0 ? 0 : delay;