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.homeconnect.internal.handler.cache;
15 import java.lang.ref.SoftReference;
16 import java.time.Duration;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
21 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
22 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
23 import org.openhab.binding.homeconnect.internal.handler.SupplierWithException;
24 import org.openhab.core.types.State;
28 * Expiring state model. Holds a state and the corresponding expiration time.
30 * @author Jonas BrĂ¼stel - Initial Contribution
33 public class ExpiringStateCache {
35 private final SupplierWithException<State> stateSupplier;
36 private final long expiry;
38 private SoftReference<@Nullable State> state = new SoftReference<>(null);
39 private long expiresAt;
42 * Create a new instance.
44 * @param expiry the duration for how long the state should be cached
45 * @param stateSupplier supplier to get current state
47 public ExpiringStateCache(Duration expiry, SupplierWithException<State> stateSupplier) {
48 this.stateSupplier = stateSupplier;
49 this.expiry = expiry.toNanos();
53 * Returns the cached or newly fetched state.
56 * @throws CommunicationException API communication exception
57 * @throws AuthorizationException oAuth authorization exception
58 * @throws ApplianceOfflineException appliance is not connected to the cloud
60 public synchronized State getState()
61 throws AuthorizationException, ApplianceOfflineException, CommunicationException {
62 State cachedValue = state.get();
63 if (cachedValue == null || isExpired()) {
64 return refreshState();
69 private State refreshState() throws AuthorizationException, ApplianceOfflineException, CommunicationException {
70 State freshValue = stateSupplier.get();
71 state = new SoftReference<>(freshValue);
72 expiresAt = calcExpiresAt();
76 private boolean isExpired() {
77 return expiresAt < System.nanoTime();
80 private long calcExpiresAt() {
81 return System.nanoTime() + expiry;