Skip to content

Optimise FutureConverters.toScala #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/main/scala/scala/compat/java8/FutureConverters.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ package scala.compat.java8
import scala.language.implicitConversions

import scala.concurrent.java8.FuturesConvertersImpl._
import scala.util.{Failure, Try}
import scala.concurrent.{ Future, Promise, ExecutionContext, ExecutionContextExecutorService, ExecutionContextExecutor }
import java.util.concurrent.{ CompletionStage, Executor, ExecutorService }
import java.util.concurrent.{CompletableFuture, CompletionStage, ExecutionException, Executor, ExecutorService}
import java.util.function.Consumer

/**
Expand Down Expand Up @@ -78,6 +79,8 @@ object FutureConverters {
def toScala[T](cs: CompletionStage[T]): Future[T] = {
cs match {
case cf: CF[T] => cf.wrapped
case cf: CompletableFuture[T] if cf.isDone =>
Future fromTry Try(cf.get()).recoverWith { case e: ExecutionException => Failure(e.getCause) }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given this code it is not clear to me that this is in fact an optimization. Is there any benchmark performed that shows what improvement this change leads to?

Copy link
Author

@t3hnar t3hnar Feb 16, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@viktorklang Might be I'm missing something, but I believe that optimised version works faster because of removal of possible context switch

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@t3hnar I suspect this to be slower: there will be one allocation for the thunk to Try.apply, then another thunk for the recoverWith function. For the other code it will be a single allocation of the P.

case _ =>
val p = new P[T](cs)
cs whenComplete p
Expand Down