2 * Copyright (c) 2010-2024 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.Nullable;
22 * {@link ShellyManagerCache} implements a cache with expiring times of the entries
24 * @author Markus Michels - Initial contribution
26 public class ShellyManagerCache<K, V> extends ConcurrentHashMap<K, V> {
28 private static final long serialVersionUID = 1L;
30 private Map<K, Long> timeMap = new ConcurrentHashMap<>();
31 private long expiryInMillis = ShellyManagerConstants.CACHE_TIMEOUT_DEF_MIN * 60 * 1000; // Default 1h
33 public ShellyManagerCache() {
37 public ShellyManagerCache(long expiryInMillis) {
38 this.expiryInMillis = expiryInMillis;
43 new CleanerThread().start();
47 public V put(K key, V value) {
48 Date date = new Date();
49 timeMap.put(key, date.getTime());
50 return super.put(key, value);
54 public void putAll(@Nullable Map<? extends K, ? extends V> m) {
56 throw new IllegalArgumentException();
58 for (K key : m.keySet()) {
60 if (value != null) { // don't allow null values
67 public V putIfAbsent(K key, V value) {
68 if (!containsKey(key)) {
69 return put(key, value);
75 class CleanerThread extends Thread {
81 Thread.sleep(expiryInMillis / 2);
82 } catch (InterruptedException e) {
87 private void cleanMap() {
88 long currentTime = new Date().getTime();
89 for (K key : timeMap.keySet()) {
90 if (currentTime > (timeMap.get(key) + expiryInMillis)) {