pekko/docs/src/test/java/jdocs/future/FutureDocTest.java

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

81 lines
2.6 KiB
Java
Raw Normal View History

/*
2022-02-04 12:36:44 +01:00
* Copyright (C) 2009-2022 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.future;
import org.apache.pekko.actor.typed.ActorSystem;
import org.apache.pekko.dispatch.Futures;
import org.apache.pekko.pattern.Patterns;
import org.apache.pekko.testkit.AkkaJUnitActorSystemResource;
import org.apache.pekko.testkit.AkkaSpec;
import org.apache.pekko.util.Timeout;
import jdocs.AbstractJavaTest;
import org.junit.ClassRule;
import org.junit.Test;
import scala.compat.java8.FutureConverters;
import scala.concurrent.Await;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
2018-08-23 22:43:17 +09:00
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
2018-03-26 14:56:20 +03:00
import static org.apache.pekko.actor.typed.javadsl.Adapter.toTyped;
import static org.apache.pekko.dispatch.Futures.future;
// #imports
import org.apache.pekko.pattern.Patterns;
// #imports
import static java.util.concurrent.TimeUnit.SECONDS;
public class FutureDocTest extends AbstractJavaTest {
@ClassRule
public static AkkaJUnitActorSystemResource actorSystemResource =
new AkkaJUnitActorSystemResource("FutureDocTest", AkkaSpec.testConf());
private final ActorSystem<Void> system = toTyped(actorSystemResource.getSystem());
2012-01-24 16:31:20 +01:00
@Test(expected = java.util.concurrent.CompletionException.class)
2012-08-20 19:49:01 +02:00
public void useAfter() throws Exception {
final ExecutionContext ec = system.executionContext();
// #after
CompletionStage<String> failWithException =
CompletableFuture.supplyAsync(
() -> {
throw new IllegalStateException("OHNOES1");
});
CompletionStage<String> delayed =
Patterns.after(Duration.ofMillis(200), system, () -> failWithException);
// #after
Future<String> future =
future(
() -> {
Thread.sleep(1000);
return "foo";
},
ec);
Future<String> result =
Futures.firstCompletedOf(
Arrays.<Future<String>>asList(future, FutureConverters.toScala(delayed)), ec);
2018-08-23 22:43:17 +09:00
Timeout timeout = Timeout.create(Duration.ofSeconds(2));
Await.result(result, timeout.duration());
2012-08-20 19:49:01 +02:00
}
2018-03-26 14:56:20 +03:00
@Test
public void useRetry() throws Exception {
// #retry
2018-03-26 14:56:20 +03:00
Callable<CompletionStage<String>> attempt = () -> CompletableFuture.completedFuture("test");
CompletionStage<String> retriedFuture =
Patterns.retry(attempt, 3, java.time.Duration.ofMillis(200), system);
// #retry
2018-03-26 14:56:20 +03:00
retriedFuture.toCompletableFuture().get(2, SECONDS);
}
}