]> git.basschouten.com Git - openhab-addons.git/blob
1ced15cfebaad66b0cfb41cb54f883bc48d68d95
[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.nibeheatpump.internal;
14
15 import java.util.concurrent.Future;
16 import java.util.concurrent.TimeUnit;
17 import java.util.concurrent.TimeoutException;
18 import java.util.concurrent.locks.Condition;
19 import java.util.concurrent.locks.Lock;
20 import java.util.concurrent.locks.ReentrantLock;
21
22 import org.openhab.binding.nibeheatpump.internal.message.NibeHeatPumpMessage;
23
24 /**
25  * The {@link NibeHeatPumpCommandResult} implements a very simple {@link Future} for {@link NibeHeatPumpMessage}s.
26  *
27  *
28  * @author Pauli Anttila - Initial contribution
29  */
30 public class NibeHeatPumpCommandResult implements Future<NibeHeatPumpMessage> {
31
32     private final Lock lock = new ReentrantLock();
33     private final Condition condition = lock.newCondition();
34
35     private NibeHeatPumpMessage result = null;
36     private boolean done = false;
37
38     @Override
39     public boolean cancel(boolean mayInterruptIfRunning) {
40         return false;
41     }
42
43     @Override
44     public boolean isCancelled() {
45         return false;
46     }
47
48     @Override
49     public boolean isDone() {
50         lock.lock();
51         try {
52             return done;
53         } finally {
54             lock.unlock();
55         }
56     }
57
58     @Override
59     public NibeHeatPumpMessage get() throws InterruptedException {
60         lock.lock();
61         try {
62             if (!done) {
63                 condition.await();
64             }
65             return result;
66         } finally {
67             lock.unlock();
68         }
69     }
70
71     @Override
72     public NibeHeatPumpMessage get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
73         lock.lock();
74         try {
75             if (!done) {
76                 final boolean timedOut = !condition.await(timeout, unit);
77                 if (timedOut) {
78                     throw new TimeoutException("waiting timed out");
79                 }
80             }
81             return result;
82         } finally {
83             lock.unlock();
84         }
85     }
86
87     public void set(final NibeHeatPumpMessage result) {
88         lock.lock();
89         try {
90             this.result = result;
91             this.done = true;
92             condition.signalAll();
93         } finally {
94             lock.unlock();
95         }
96     }
97 }