summaryrefslogtreecommitdiff
path: root/core/java/com/android/internal/inputmethod/CompletableFutureUtil.java
blob: ec10e014384a4beab5a2c6b7be13b7f91d9fe911 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.inputmethod;

import android.annotation.AnyThread;
import android.annotation.DurationMillisLong;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.util.Log;

import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * A set of helper methods to retrieve result values from {@link CompletableFuture}.
 */
public final class CompletableFutureUtil {
    /**
     * Not intended to be instantiated.
     */
    private CompletableFutureUtil() {
    }

    @AnyThread
    @Nullable
    private static <T> T getValueOrRethrowErrorInternal(@NonNull CompletableFuture<T> future) {
        boolean interrupted = false;
        try {
            while (true) {
                try {
                    return future.get();
                } catch (ExecutionException e) {
                    final Throwable cause = e.getCause();
                    throw new RuntimeException(cause.getMessage(), cause.getCause());
                } catch (InterruptedException e) {
                    interrupted = true;
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }

    @AnyThread
    @Nullable
    private static <T> T getValueOrNullInternal(@NonNull CompletableFuture<T> future,
            @Nullable String tag, @Nullable String methodName,
            @DurationMillisLong long timeoutMillis, @Nullable CancellationGroup cancellationGroup) {
        // We intentionally do not use CompletableFuture.anyOf() to avoid additional object
        // allocations.
        final boolean needsToUnregister = cancellationGroup != null
                && cancellationGroup.tryRegisterFutureOrCancelImmediately(future);
        boolean interrupted = false;
        try {
            while (true) {
                try {
                    return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
                } catch (CompletionException e) {
                    if (e.getCause() instanceof CancellationException) {
                        logCancellationInternal(tag, methodName);
                        return null;
                    }
                    logErrorInternal(tag, methodName, e.getMessage());
                    return null;
                } catch (CancellationException e) {
                    logCancellationInternal(tag, methodName);
                    return null;
                } catch (InterruptedException e) {
                    interrupted = true;
                } catch (TimeoutException e) {
                    logTimeoutInternal(tag, methodName, timeoutMillis);
                    return null;
                } catch (Throwable e) {
                    logErrorInternal(tag, methodName, e.getMessage());
                    return null;
                }
            }
        } finally {
            if (needsToUnregister) {
                cancellationGroup.unregisterFuture(future);
            }
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }

    @AnyThread
    private static void logTimeoutInternal(@Nullable String tag, @Nullable String methodName,
            @DurationMillisLong long timeout) {
        if (tag == null || methodName == null) {
            return;
        }
        Log.w(tag, methodName + " didn't respond in " + timeout + " msec.");
    }

    @AnyThread
    private static void logErrorInternal(@Nullable String tag, @Nullable String methodName,
            @Nullable String errorString) {
        if (tag == null || methodName == null) {
            return;
        }
        Log.w(tag, methodName + " was failed with an exception=" + errorString);
    }

    @AnyThread
    private static void logCancellationInternal(@Nullable String tag, @Nullable String methodName) {
        if (tag == null || methodName == null) {
            return;
        }
        Log.w(tag, methodName + " was cancelled.");
    }

    /**
     * Return the result of the given {@link CompletableFuture<T>}.
     *
     * <p>This method may throw exception is the task is completed with an error.</p>
     *
     * @param future the object to extract the result from.
     * @param <T> type of the result.
     * @return the result.
     */
    @AnyThread
    @Nullable
    public static <T> T getResult(@NonNull CompletableFuture<T> future) {
        return getValueOrRethrowErrorInternal(future);
    }

    /**
     * Return the result of the given {@link CompletableFuture<Boolean>}.
     *
     * <p>This method may throw exception is the task is completed with an error.</p>
     *
     * @param future the object to extract the result from.
     * @return the result.
     */
    @AnyThread
    public static boolean getBooleanResult(@NonNull CompletableFuture<Boolean> future) {
        return getValueOrRethrowErrorInternal(future);
    }

    /**
     * Return the result of the given {@link CompletableFuture<Integer>}.
     *
     * <p>This method may throw exception is the task is completed with an error.</p>
     *
     * @param future the object to extract the result from.
     * @return the result.
     */
    @AnyThread
    public static int getIntegerResult(@NonNull CompletableFuture<Integer> future) {
        return getValueOrRethrowErrorInternal(future);
    }

    /**
     * Return the result of the given {@link CompletableFuture<Boolean>}.
     *
     * <p>This method is agnostic to {@link Thread#interrupt()}.</p>
     *
     * <p>CAVEAT: when {@code cancellationGroup} is specified and it is signalled, {@code future}
     * will be cancelled permanently.  You have to duplicate the {@link CompletableFuture} if you
     * want to avoid this side-effect.</p>
     *
     * @param future the object to extract the result from.
     * @param tag tag name for logging. Pass {@code null} to disable logging.
     * @param methodName method name for logging. Pass {@code null} to disable logging.
     * @param cancellationGroup an optional {@link CancellationGroup} to cancel {@code future}
     *                          object. Can be {@code null}.
     * @param timeoutMillis length of the timeout in millisecond.
     * @return the result if it is completed within the given timeout. {@code false} otherwise.
     */
    @AnyThread
    public static boolean getResultOrFalse(@NonNull CompletableFuture<Boolean> future,
            @Nullable String tag, @Nullable String methodName,
            @Nullable CancellationGroup cancellationGroup,
            @DurationMillisLong long timeoutMillis) {
        final Boolean obj = getValueOrNullInternal(future, tag, methodName, timeoutMillis,
                cancellationGroup);
        return obj != null ? obj : false;
    }

    /**
     * Return the result of the given {@link CompletableFuture<Integer>}.
     *
     * <p>This method is agnostic to {@link Thread#interrupt()}.</p>
     *
     * <p>CAVEAT: when {@code cancellationGroup} is specified and it is signalled, {@code future}
     * will be cancelled permanently.  You have to duplicate the {@link CompletableFuture} if you
     * want to avoid this side-effect.</p>
     *
     * @param future the object to extract the result from.
     * @param tag tag name for logging. Pass {@code null} to disable logging.
     * @param methodName method name for logging. Pass {@code null} to disable logging.
     * @param cancellationGroup an optional {@link CancellationGroup} to cancel {@code future}
     *                          object. Can be {@code null}.
     * @param timeoutMillis length of the timeout in millisecond.
     * @return the result if it is completed within the given timeout. {@code 0} otherwise.
     */
    @AnyThread
    public static int getResultOrZero(@NonNull CompletableFuture<Integer> future,
            @Nullable String tag, @Nullable String methodName,
            @Nullable CancellationGroup cancellationGroup, @DurationMillisLong long timeoutMillis) {
        final Integer obj = getValueOrNullInternal(future, tag, methodName, timeoutMillis,
                cancellationGroup);
        return obj != null ? obj : 0;
    }

    /**
     * Return the result of the given {@link CompletableFuture<T>}.
     *
     * <p>This method is agnostic to {@link Thread#interrupt()}.</p>
     *
     * <p>CAVEAT: when {@code cancellationGroup} is specified and it is signalled, {@code future}
     * will be cancelled permanently.  You have to duplicate the {@link CompletableFuture} if you
     * want to avoid this side-effect.</p>
     *
     * @param future the object to extract the result from.
     * @param tag tag name for logging. Pass {@code null} to disable logging.
     * @param methodName method name for logging. Pass {@code null} to disable logging.
     * @param cancellationGroup an optional {@link CancellationGroup} to cancel {@code future}
     *                          object. Can be {@code null}.
     * @param timeoutMillis length of the timeout in millisecond.
     * @param <T> Type of the result.
     * @return the result if it is completed within the given timeout. {@code null} otherwise.
     */
    @AnyThread
    @Nullable
    public static <T> T getResultOrNull(@NonNull CompletableFuture<T> future, @Nullable String tag,
            @Nullable String methodName, @Nullable CancellationGroup cancellationGroup,
            @DurationMillisLong long timeoutMillis) {
        return getValueOrNullInternal(future, tag, methodName, timeoutMillis, cancellationGroup);
    }
}