Skip to content

Commit

Permalink
Introduce listenablefuture and failureaccess artifacts, plus Internal…
Browse files Browse the repository at this point in the history
…FutureFailureAccess.

(taken over from CL 210155310 to add Maven setup)

It provides a direct access to the cause of any failures,
so we can avoid unnecessary allocation of an exception.

Design discussion: https://docs.google.com/document/d/1_RVTtztq5pqrhs0srvJWHMI7PT1tA71--iaauV2l5UA/edit

RELNOTES=Created separate `listenablefuture` and `failureaccess` artifacts, the latter containing the new `InternalFutureFailureAccess`. For more details about `listenablefuture`, see [this announcement](https://groups.google.com/d/topic/guava-announce/Km82fZG68Sw).

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=212516713
  • Loading branch information
cpovirk committed Sep 12, 2018
1 parent eb3a9f4 commit b62d529
Show file tree
Hide file tree
Showing 19 changed files with 808 additions and 11 deletions.
Expand Up @@ -18,6 +18,7 @@

import static com.google.common.truth.Truth.assertThat;

import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -34,6 +35,8 @@ public class AbstractFutureCancellationCauseTest extends TestCase {

private ClassLoader oldClassLoader;
private URLClassLoader classReloader;
private Class<?> settableFutureClass;
private Class<?> abstractFutureClass;

@Override
protected void setUp() throws Exception {
Expand Down Expand Up @@ -68,6 +71,8 @@ public Class<?> loadClass(String name) throws ClassNotFoundException {
};
oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classReloader);
abstractFutureClass = classReloader.loadClass(AbstractFuture.class.getName());
settableFutureClass = classReloader.loadClass(SettableFuture.class.getName());
}

@Override
Expand All @@ -82,6 +87,7 @@ public void testCancel_notDoneNoInterrupt() throws Exception {
assertTrue(future.cancel(false));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
assertNull(tryInternalFastPathGetFailure(future));
try {
future.get();
fail("Expected CancellationException");
Expand All @@ -95,6 +101,7 @@ public void testCancel_notDoneInterrupt() throws Exception {
assertTrue(future.cancel(true));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
assertNull(tryInternalFastPathGetFailure(future));
try {
future.get();
fail("Expected CancellationException");
Expand Down Expand Up @@ -153,7 +160,13 @@ public void addListener(Runnable runnable, Executor executor) {
}

private Future<?> newFutureInstance() throws Exception {
return (Future<?>)
classReloader.loadClass(SettableFuture.class.getName()).getMethod("create").invoke(null);
return (Future<?>) settableFutureClass.getMethod("create").invoke(null);
}

private Throwable tryInternalFastPathGetFailure(Future<?> future) throws Exception {
Method tryInternalFastPathGetFailureMethod =
abstractFutureClass.getDeclaredMethod("tryInternalFastPathGetFailure");
tryInternalFastPathGetFailureMethod.setAccessible(true);
return (Throwable) tryInternalFastPathGetFailureMethod.invoke(future);
}
}
Expand Up @@ -22,6 +22,7 @@
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -971,6 +972,113 @@ public void run() {
t.join();
}

public void testTrustedGetFailure_Completed() {
SettableFuture<String> future = SettableFuture.create();
future.set("261");
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testTrustedGetFailure_Failed() {
SettableFuture<String> future = SettableFuture.create();
Throwable failure = new Throwable();
future.setException(failure);
assertThat(future.tryInternalFastPathGetFailure()).isEqualTo(failure);
}

public void testTrustedGetFailure_NotCompleted() {
SettableFuture<String> future = SettableFuture.create();
assertThat(future.isDone()).isFalse();
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testTrustedGetFailure_CanceledNoCause() {
SettableFuture<String> future = SettableFuture.create();
future.cancel(false);
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testGetFailure_Completed() {
AbstractFuture<String> future = new AbstractFuture<String>() {};
future.set("261");
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testGetFailure_Failed() {
AbstractFuture<String> future = new AbstractFuture<String>() {};
final Throwable failure = new Throwable();
future.setException(failure);
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testGetFailure_NotCompleted() {
AbstractFuture<String> future = new AbstractFuture<String>() {};
assertThat(future.isDone()).isFalse();
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testGetFailure_CanceledNoCause() {
AbstractFuture<String> future = new AbstractFuture<String>() {};
future.cancel(false);
assertThat(future.tryInternalFastPathGetFailure()).isNull();
}

public void testForwardExceptionFastPath() throws Exception {
class FailFuture extends InternalFutureFailureAccess implements ListenableFuture<String> {
Throwable failure;

FailFuture(Throwable throwable) {
failure = throwable;
}

@Override
public boolean cancel(boolean mayInterruptIfRunning) {
throw new AssertionFailedError("cancel shouldn't be called on this object");
}

@Override
public boolean isCancelled() {
return false;
}

@Override
public boolean isDone() {
return true;
}

@Override
public String get() throws InterruptedException, ExecutionException {
throw new AssertionFailedError("get() shouldn't be called on this object");
}

@Override
public String get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return get();
}

@Override
protected Throwable tryInternalFastPathGetFailure() {
return failure;
}

@Override
public void addListener(Runnable listener, Executor executor) {
throw new AssertionFailedError("addListener() shouldn't be called on this object");
}
}

final RuntimeException exception = new RuntimeException("you still didn't say the magic word!");
SettableFuture<String> normalFuture = SettableFuture.create();
normalFuture.setFuture(new FailFuture(exception));
assertTrue(normalFuture.isDone());
try {
normalFuture.get();
fail();
} catch (ExecutionException e) {
assertSame(exception, e.getCause());
}
}

private static void awaitUnchecked(final CyclicBarrier barrier) {
try {
barrier.await();
Expand Down
10 changes: 10 additions & 0 deletions android/guava/pom.xml
Expand Up @@ -16,6 +16,16 @@
much more.
</description>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>listenablefuture</artifactId>
<version>9999.0-empty-to-avoid-conflict-with-guava</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
Expand Down
Expand Up @@ -20,6 +20,8 @@

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
import com.google.common.util.concurrent.internal.InternalFutures;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.ForOverride;
import com.google.j2objc.annotations.ReflectionSupport;
Expand Down Expand Up @@ -62,7 +64,8 @@
@SuppressWarnings("ShortCircuitBoolean") // we use non-short circuiting comparisons intentionally
@GwtCompatible(emulated = true)
@ReflectionSupport(value = ReflectionSupport.Level.FULL)
public abstract class AbstractFuture<V> implements ListenableFuture<V> {
public abstract class AbstractFuture<V> extends InternalFutureFailureAccess
implements ListenableFuture<V> {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||

private static final boolean GENERATE_CANCELLATION_CAUSES =
Expand Down Expand Up @@ -847,6 +850,13 @@ private static Object getFutureValue(ListenableFuture<?> future) {
}
return v;
}
if (future instanceof InternalFutureFailureAccess) {
Throwable throwable =
InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future);
if (throwable != null) {
return new Failure(throwable);
}
}
boolean wasCancelled = future.isCancelled();
// Don't allocate a CancellationException if it's not necessary
if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) {
Expand Down Expand Up @@ -967,6 +977,39 @@ private static void complete(AbstractFuture<?> future) {
@ForOverride
protected void afterDone() {}

// TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL.
/**
* Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i>
* return the cause of the failure. "Failure" means specifically "completed with an exception"; it
* does not include "was cancelled." To be explicit: If this method returns a non-null value,
* then:
*
* <ul>
* <li>{@code isDone()} must return {@code true}
* <li>{@code isCancelled()} must return {@code false}
* <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the
* return value of this method as its cause
* </ul>
*
* <p>This method is {@code protected} so that classes like {@code
* com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an
* instance method. In the unlikely event that you need to call this method, call {@link
* InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}.
*
* @since 27.0
*/
@Override
@NullableDecl
protected final Throwable tryInternalFastPathGetFailure() {
if (this instanceof Trusted) {
Object obj = value;
if (obj instanceof Failure) {
return ((Failure) obj).exception;
}
}
return null;
}

/**
* Returns the exception that this {@code Future} completed with. This includes completion through
* a call to {@link #setException} or {@link #setFuture setFuture}{@code (failedFuture)} but not
Expand Down
Expand Up @@ -14,7 +14,6 @@

package com.google.common.util.concurrent;

import com.google.common.annotations.GwtCompatible;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
Expand All @@ -29,6 +28,8 @@
* href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
* ListenableFuture}</a>.
*
* <p>This class is GWT-compatible.
*
* <h3>Purpose</h3>
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
Expand Down Expand Up @@ -97,7 +98,6 @@
* @author Nishant Thakkar
* @since 1.0
*/
@GwtCompatible
public interface ListenableFuture<V> extends Future<V> {
/**
* Registers a listener to be {@linkplain Executor#execute(Runnable) run} on the given executor.
Expand Down
2 changes: 2 additions & 0 deletions futures/README.md
@@ -0,0 +1,2 @@
The modules under this directory will be released exactly once each. Once that
happens, there will be no need to ever update any files here.
46 changes: 46 additions & 0 deletions futures/failureaccess/pom.xml
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.google.guava</groupId>
<artifactId>guava-parent</artifactId>
<version>26.0-android</version>
</parent>
<artifactId>failureaccess</artifactId>
<version>1.0</version>
<name>Guava InternalFutureFailureAccess and InternalFutures</name>
<description>
Contains
com.google.common.util.concurrent.internal.InternalFutureFailureAccess and
InternalFutures. Most users will never need to use this artifact. Its
classes is conceptually a part of Guava, but they're in this separate
artifact so that Android libraries can use them without pulling in all of
Guava (just as they can use ListenableFuture by depending on the
listenablefuture artifact).
</description>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-docs</id>
</execution>
<execution>
<id>generate-javadoc-site-report</id>
<phase>site</phase>
<goals><goal>javadoc</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2018 The Guava Authors
*
* 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.google.common.util.concurrent.internal;

/**
* A future that, if it fails, may <i>optionally</i> provide access to the cause of the failure.
*
* <p>This class is used only for micro-optimization. Standard {@code Future} utilities benefit from
* this optimization, so there is no need to specialize methods to return or accept this type
* instead of {@code ListenableFuture}.
*
* <p>This class is GWT-compatible.
*
* @since {@code com.google.guava:failureaccess:1.0}, which was added as a dependency of Guava in
* Guava 27.0
*/
public abstract class InternalFutureFailureAccess {
/** Constructor for use by subclasses. */
protected InternalFutureFailureAccess() {}

/**
* Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i>
* return the cause of the failure. "Failure" means specifically "completed with an exception"; it
* does not include "was cancelled." To be explicit: If this method returns a non-null value,
* then:
*
* <ul>
* <li>{@code isDone()} must return {@code true}
* <li>{@code isCancelled()} must return {@code false}
* <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the
* return value of this method as its cause
* </ul>
*
* <p>This method is {@code protected} so that classes like {@code
* com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an
* instance method. In the unlikely event that you need to call this method, call {@link
* InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}.
*/
protected abstract Throwable tryInternalFastPathGetFailure();
}

0 comments on commit b62d529

Please sign in to comment.