]> git.basschouten.com Git - openhab-addons.git/blob
fe99583edb5fa2c54efd2116005ee874653dd283
[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.ambientweather.internal.util;
14
15 import java.util.Collections;
16 import java.util.Iterator;
17 import java.util.SortedMap;
18 import java.util.TreeMap;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21
22 /**
23  * The {@link SlidingTimeWindow} is responsible for managing a set of
24  * time-based values. This class is used to calculate trends over time.
25  *
26  * @author Mark Hilbush - Initial contribution
27  */
28 @NonNullByDefault
29 class SlidingTimeWindow<T> {
30     protected long period = 0;
31     protected final SortedMap<Long, T> storage = Collections.synchronizedSortedMap(new TreeMap<>());
32
33     /**
34      * Create a sliding time window for the provided time period
35      */
36     public SlidingTimeWindow(long period) {
37         this.period = period;
38     }
39
40     public void put(T value) {
41         storage.put(System.currentTimeMillis(), value);
42     }
43
44     public void removeOldEntries() {
45         long old = System.currentTimeMillis() - period;
46         synchronized (storage) {
47             for (Iterator<Long> iterator = storage.keySet().iterator(); iterator.hasNext();) {
48                 long time = iterator.next();
49                 if (time < old) {
50                     iterator.remove();
51                 }
52             }
53         }
54     }
55 }