Skip to content
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

Enhancement: for-yield with Future Monad is a common concurrency bug #282

Open
philliptaylorpro opened this issue Mar 6, 2020 · 1 comment

Comments

@philliptaylorpro
Copy link

It would be good if Scapegoat could see this:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

for {
    a <- Future { "a" }
    b <- Future { "b" }
} yield { println(a + b) }

and warn Missed concurrency opportunity. Future b waits for Future a but may not need to

Conditions:

  • For yield
  • Top level Monad is scala.concurrent.Future[_]
  • Future { "b" } doesn't refer to variable A

Details:
A for-yield statement is a series of flatMaps with a map at the end, therefore the code above waits for a to return successfully before starting b. By rearranging the for-loop you can theoretically speed up the application. For example this would be faster assuming the Futures were slower:

Future.sequence(Seq(Future { "a" }, Future { "b" })).map {
    case a :: b :: Nil => println(a + b)
    case _ =>
}

It's just an idea.

@philliptaylorpro philliptaylorpro changed the title Enhancement: for {} with Future Monad is a common concurrency bug Enhancement: for-yield with Future Monad is a common concurrency bug Mar 6, 2020
@sksamuel
Copy link
Collaborator

sksamuel commented May 2, 2020

Great idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants