Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 8a4ab674 authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Use CompletableFuture instead"

parents 4f57e27d ba8cdf5d
Loading
Loading
Loading
Loading
+19 −17
Original line number Diff line number Diff line
@@ -34,7 +34,7 @@ import android.view.inputmethod.InputContentInfo;
import android.view.inputmethod.SurroundingText;

import com.android.internal.inputmethod.CancellationGroup;
import com.android.internal.inputmethod.Completable;
import com.android.internal.inputmethod.CompletableFutureUtil;
import com.android.internal.inputmethod.IInputContextInvoker;
import com.android.internal.inputmethod.ImeTracing;
import com.android.internal.inputmethod.InputConnectionProtoDumper;
@@ -42,6 +42,7 @@ import com.android.internal.view.IInputContext;
import com.android.internal.view.IInputMethod;

import java.lang.ref.WeakReference;
import java.util.concurrent.CompletableFuture;

/**
 * Takes care of remote method invocations of {@link InputConnection} in the IME side.
@@ -96,8 +97,8 @@ final class RemoteInputConnection implements InputConnection {
            return null;
        }

        final Completable.CharSequence value = mInvoker.getTextAfterCursor(length, flags);
        final CharSequence result = Completable.getResultOrNull(
        final CompletableFuture<CharSequence> value = mInvoker.getTextAfterCursor(length, flags);
        final CharSequence result = CompletableFutureUtil.getResultOrNull(
                value, TAG, "getTextAfterCursor()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -120,8 +121,8 @@ final class RemoteInputConnection implements InputConnection {
            return null;
        }

        final Completable.CharSequence value = mInvoker.getTextBeforeCursor(length, flags);
        final CharSequence result = Completable.getResultOrNull(
        final CompletableFuture<CharSequence> value = mInvoker.getTextBeforeCursor(length, flags);
        final CharSequence result = CompletableFutureUtil.getResultOrNull(
                value, TAG, "getTextBeforeCursor()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -144,8 +145,8 @@ final class RemoteInputConnection implements InputConnection {
            // This method is not implemented.
            return null;
        }
        final Completable.CharSequence value = mInvoker.getSelectedText(flags);
        final CharSequence result = Completable.getResultOrNull(
        final CompletableFuture<CharSequence> value = mInvoker.getSelectedText(flags);
        final CharSequence result = CompletableFutureUtil.getResultOrNull(
                value, TAG, "getSelectedText()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -181,9 +182,9 @@ final class RemoteInputConnection implements InputConnection {
            // This method is not implemented.
            return null;
        }
        final Completable.SurroundingText value = mInvoker.getSurroundingText(beforeLength,
        final CompletableFuture<SurroundingText> value = mInvoker.getSurroundingText(beforeLength,
                afterLength, flags);
        final SurroundingText result = Completable.getResultOrNull(
        final SurroundingText result = CompletableFutureUtil.getResultOrNull(
                value, TAG, "getSurroundingText()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -202,8 +203,8 @@ final class RemoteInputConnection implements InputConnection {
            return 0;
        }

        final Completable.Int value = mInvoker.getCursorCapsMode(reqModes);
        final int result = Completable.getResultOrZero(
        final CompletableFuture<Integer> value = mInvoker.getCursorCapsMode(reqModes);
        final int result = CompletableFutureUtil.getResultOrZero(
                value, TAG, "getCursorCapsMode()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -222,8 +223,8 @@ final class RemoteInputConnection implements InputConnection {
            return null;
        }

        final Completable.ExtractedText value = mInvoker.getExtractedText(request, flags);
        final ExtractedText result = Completable.getResultOrNull(
        final CompletableFuture<ExtractedText> value = mInvoker.getExtractedText(request, flags);
        final ExtractedText result = CompletableFutureUtil.getResultOrNull(
                value, TAG, "getExtractedText()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);

        final InputMethodServiceInternal inputMethodService = mInputMethodService.get();
@@ -371,8 +372,8 @@ final class RemoteInputConnection implements InputConnection {
            // This method is not implemented.
            return false;
        }
        final Completable.Boolean value = mInvoker.requestCursorUpdates(cursorUpdateMode);
        return Completable.getResultOrFalse(value, TAG, "requestCursorUpdates()",
        final CompletableFuture<Boolean> value = mInvoker.requestCursorUpdates(cursorUpdateMode);
        return CompletableFutureUtil.getResultOrFalse(value, TAG, "requestCursorUpdates()",
                mCancellationGroup, MAX_WAIT_TIME_MILLIS);
    }

@@ -407,8 +408,9 @@ final class RemoteInputConnection implements InputConnection {
            inputMethodService.exposeContent(inputContentInfo, this);
        }

        final Completable.Boolean value = mInvoker.commitContent(inputContentInfo, flags, opts);
        return Completable.getResultOrFalse(
        final CompletableFuture<Boolean> value =
                mInvoker.commitContent(inputContentInfo, flags, opts);
        return CompletableFutureUtil.getResultOrFalse(
                value, TAG, "commitContent()", mCancellationGroup, MAX_WAIT_TIME_MILLIS);
    }

+31 −14
Original line number Diff line number Diff line
@@ -23,49 +23,66 @@ import android.annotation.Nullable;
import com.android.internal.annotations.GuardedBy;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CompletableFuture;

/**
 * A utility class, which works as both a factory class of a cancellation signal to cancel
 * all the completable objects.
 *
 * <p>TODO: Make this lock-free.</p>
 */
public final class CancellationGroup {
    private final Object mLock = new Object();

    /**
     * List of {@link CountDownLatch}, which can be used to propagate {@link #cancelAll()} to
     * List of {@link CompletableFuture}, which can be used to propagate {@link #cancelAll()} to
     * completable objects.
     *
     * <p>This will be lazily instantiated to avoid unnecessary object allocations.</p>
     */
    @Nullable
    @GuardedBy("mLock")
    private ArrayList<CountDownLatch> mLatchList = null;
    private ArrayList<CompletableFuture<?>> mFutureList = null;

    @GuardedBy("mLock")
    private boolean mCanceled = false;

    /**
     * Tries to register the given {@link CompletableFuture} into the callback list if this
     * {@link CancellationGroup} is not yet cancelled.
     *
     * <p>If this {@link CancellationGroup} is already cancelled, then this method will immediately
     * call {@link CompletableFuture#cancel(boolean)} then return {@code false}.</p>
     *
     * <p>When this method returns {@code true}, call {@link #unregisterFuture(CompletableFuture)}
     * to remove the unnecessary object reference.</p>
     *
     * @param future {@link CompletableFuture} to be added to the cancellation callback list.
     * @return {@code true} if the given {@code future} is added to the callback list.
     *         {@code false} otherwise.
     */
    @AnyThread
    boolean registerLatch(@NonNull CountDownLatch latch) {
    boolean tryRegisterFutureOrCancelImmediately(@NonNull CompletableFuture<?> future) {
        synchronized (mLock) {
            if (mCanceled) {
                future.cancel(false);
                return false;
            }
            if (mLatchList == null) {
            if (mFutureList == null) {
                // Set the initial capacity to 1 with an assumption that usually there is up to 1
                // on-going operation.
                mLatchList = new ArrayList<>(1);
                mFutureList = new ArrayList<>(1);
            }
            mLatchList.add(latch);
            mFutureList.add(future);
            return true;
        }
    }

    @AnyThread
    void unregisterLatch(@NonNull CountDownLatch latch) {
    void unregisterFuture(@NonNull CompletableFuture<?> future) {
        synchronized (mLock) {
            if (mLatchList != null) {
                mLatchList.remove(latch);
            if (mFutureList != null) {
                mFutureList.remove(future);
            }
        }
    }
@@ -80,10 +97,10 @@ public final class CancellationGroup {
        synchronized (mLock) {
            if (!mCanceled) {
                mCanceled = true;
                if (mLatchList != null) {
                    mLatchList.forEach(CountDownLatch::countDown);
                    mLatchList.clear();
                    mLatchList = null;
                if (mFutureList != null) {
                    mFutureList.forEach(future -> future.cancel(false));
                    mFutureList.clear();
                    mFutureList = null;
                }
            }
        }
+0 −558

File deleted.

Preview size limit exceeded, changes collapsed.

+253 −0
Original line number Diff line number Diff line
/*
 * 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);
    }
}
+55 −49

File changed.

Preview size limit exceeded, changes collapsed.

Loading