]> git.basschouten.com Git - openhab-addons.git/blob
568fd48ef4ec168172aa5670661c91fdd12d8516
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.sagercaster.internal.handler;
14
15 import java.util.Optional;
16 import java.util.SortedMap;
17 import java.util.TreeMap;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20
21 /**
22  * The {@link ExpiringMap} is responsible for storing a list of values of class T
23  * Values older than eldestAge are discarded at each insert of a new one
24  *
25  * @author GaĆ«l L'hopital - Initial contribution
26  */
27 @NonNullByDefault
28 class ExpiringMap<T> {
29     private final SortedMap<Long, T> values = new TreeMap<>();
30     private Optional<T> agedValue = Optional.empty();
31     private long eldestAge = 0;
32
33     public void setObservationPeriod(long eldestAge) {
34         this.eldestAge = eldestAge;
35     }
36
37     public void put(T newValue) {
38         long now = System.currentTimeMillis();
39         values.put(now, newValue);
40         values.keySet().stream().filter(key -> key < now - eldestAge).findFirst().ifPresent(eldest -> {
41             agedValue = Optional.ofNullable(values.get(eldest));
42             values.entrySet().removeIf(map -> map.getKey() <= eldest);
43         });
44     }
45
46     public Optional<T> getAgedValue() {
47         return agedValue;
48     }
49 }