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.shelly.internal.manager;
15 import java.util.Date;
17 import java.util.concurrent.ConcurrentHashMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
23 * {@link ShellyManagerCache} implements a cache with expiring times of the entries
25 * @author Markus Michels - Initial contribution
28 public class ShellyManagerCache<K, V> extends ConcurrentHashMap<K, V> {
30 private static final long serialVersionUID = 1L;
32 private Map<K, Long> timeMap = new ConcurrentHashMap<K, Long>();
33 private long expiryInMillis = ShellyManagerConstants.CACHE_TIMEOUT_DEF_MIN * 60 * 1000; // Default 1h
35 public ShellyManagerCache() {
39 public ShellyManagerCache(long expiryInMillis) {
40 this.expiryInMillis = expiryInMillis;
45 new CleanerThread().start();
49 public @Nullable V put(K key, V value) {
50 Date date = new Date();
51 timeMap.put(key, date.getTime());
52 V returnVal = super.put(key, value);
57 public void putAll(@Nullable Map<? extends K, ? extends V> m) {
59 throw new IllegalArgumentException();
61 for (K key : m.keySet()) {
63 if (value != null) { // don't allow null values
70 public @Nullable V putIfAbsent(K key, V value) {
71 if (!containsKey(key)) {
72 return put(key, value);
78 class CleanerThread extends Thread {
84 Thread.sleep(expiryInMillis / 2);
85 } catch (InterruptedException e) {
90 @SuppressWarnings("null")
91 private void cleanMap() {
92 long currentTime = new Date().getTime();
93 for (K key : timeMap.keySet()) {
94 if (currentTime > (timeMap.get(key) + expiryInMillis)) {