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.oceanic.internal;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.locks.ReentrantLock;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * The {@link Throttler} is helper class that regulates the frequency at which messages/packets are sent to
25 * @author Karel Goderis - Initial Contribution
27 public class Throttler {
29 private static Logger logger = LoggerFactory.getLogger(Throttler.class);
31 public static final long INTERVAL = 1000;
33 private static ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();
34 private static ConcurrentHashMap<String, Long> timestamps = new ConcurrentHashMap<>();
36 public static void lock(String key) {
37 if (!locks.containsKey(key)) {
38 locks.put(key, new ReentrantLock());
41 locks.get(key).lock();
43 if (timestamps.get(key) != null) {
44 long lastStamp = timestamps.get(key);
45 long timeToWait = Math.max(INTERVAL - (System.currentTimeMillis() - lastStamp), 0);
48 Thread.sleep(timeToWait);
49 } catch (InterruptedException e) {
50 logger.error("An exception occurred while putting the thread to sleep : '{}'", e.getMessage());
56 public static void unlock(String key) {
57 if (locks.containsKey(key)) {
58 timestamps.put(key, System.currentTimeMillis());
59 locks.get(key).unlock();
63 public static void lock() {
64 for (ReentrantLock aLock : locks.values()) {
70 for (Long aStamp : timestamps.values()) {
71 if (aStamp > lastStamp) {
76 long timeToWait = Math.max(INTERVAL - (System.currentTimeMillis() - lastStamp), 0);
79 Thread.sleep(timeToWait);
80 } catch (InterruptedException e) {
81 logger.error("An exception occurred while putting the thread to sleep : '{}'", e.getMessage());
86 public static void unlock() {
87 for (String key : locks.keySet()) {
88 if (locks.get(key).isHeldByCurrentThread()) {
89 timestamps.put(key, System.currentTimeMillis());
90 locks.get(key).unlock();