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

Reference implementation #46

Open
TomasMikula opened this issue Mar 3, 2021 · 0 comments
Open

Reference implementation #46

TomasMikula opened this issue Mar 3, 2021 · 0 comments
Labels
enhancement New feature or improvement of programmer experience

Comments

@TomasMikula
Copy link
Owner

TomasMikula commented Mar 3, 2021

The problem with the current Future-based implementation

Futures don't support removing listeners. This leads to a couple of problems.

No support for cancellation

There is no way to let a Future know that we are no longer interested in its result, not to mention to cascade that information to upstream Futures.

Resource leaks

Some recursive programs may lead to arbitrarily long chains of Promises.

To illustrate the problem, let's try to define our own flatMap method on Future:

def flatMap[A, B](fa: Future[A])(f: A => Future[B]): Future[B] = {
  val pb = Promise[B]()
  fa.onComplete {
    case Success(a) => pb.completeWith(f(a))
    case Failure(e) => pb.failure(e)
  }
  pb.future
}

Now imagine an infinite chain of such flatMaps, as in

def loop(): Future[Unit] = {
  // using *our* flatMap defined above
  flatMap(step()) { _ =>
    loop()
  }
}

def step(): Future[Unit] = ???

loop() will create an infinite chain of Promises, thus leaking resources.

This problem does not occur with Future's flatMap method, because it has a specialized implementation that avoids building up a chain of promises by re-linking the listeners. That's something not available to client code like the Libretto implementation.

Now, Libretto uses constructs with Promises like the one in the above implementation of flatMap, but not exactly flatMaps.

Suggestion for a correct reference implementation

Avoid Scala Futures altogether. Instead, introduce our own primitive that gives control over listeners. Also, it need not be as general purpose as Future, but can exploit Libretto specifics, such as having exactly one listener.

@TomasMikula TomasMikula added the enhancement New feature or improvement of programmer experience label Mar 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or improvement of programmer experience
Projects
None yet
Development

No branches or pull requests

1 participant