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.time.Duration;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ConcurrentMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
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.thing.ChannelUID;
25 import org.openhab.core.types.State;
26 import org.openhab.core.types.UnDefType;
29 * This is a simple expiring state cache implementation. The state value expires after the
30 * specified duration has passed since the item was created.
32 * @author Jonas BrĂ¼stel - Initial contribution
35 public class ExpiringStateMap {
36 private final Duration expiry;
37 private final ConcurrentMap<ChannelUID, ExpiringStateCache> items;
42 * @param expiry expiry duration
44 public ExpiringStateMap(Duration expiry) {
46 this.items = new ConcurrentHashMap<>();
50 * Get cached value or retrieve new state value via supplier.
52 * @param channelUID cache key / channel uid
53 * @param supplier supplier
54 * @return current state
55 * @throws CommunicationException API communication exception
56 * @throws AuthorizationException oAuth authorization exception
57 * @throws ApplianceOfflineException appliance is not connected to the cloud
59 public State putIfAbsentAndGet(ChannelUID channelUID, SupplierWithException<State> supplier)
60 throws AuthorizationException, ApplianceOfflineException, CommunicationException {
61 items.putIfAbsent(channelUID, new ExpiringStateCache(expiry, supplier));
63 final ExpiringStateCache item = items.get(channelUID);
65 return UnDefType.UNDEF;
67 return item.getState();