Unexpected Future[Unit].map behavior

570 views
Skip to first unread message

Chris Toomey

unread,
Dec 4, 2014, 7:17:33 PM12/4/14
to scala...@googlegroups.com
I'm using Future.apply to wrap an asynchronous computation (DB access) in a Future[Unit], call it f.

I'm then passing a function g to f.map that should be executed when f completes.  However g is being executed before f completes, hence before it's known if f will complete successfully or not.

Is this not a bug?  The Future.map documentation says "Creates a new future by applying a function to the successful result of this future. If this future is completed with an exception then the new future will also contain this exception."  So it can't be right for g to be executed before f has completed, esp. since f may throw an exception in which case g shouldn't be executed.

I'm using Scala 2.11.1.

thx,
Chris

Jon Pretty

unread,
Dec 4, 2014, 8:18:26 PM12/4/14
to Chris Toomey, scala-user
Hi Chris,

Can you work out the differences between your non-working version and this?

Future {
  Thread.sleep(1000); println("one")
} map { unit =>
  Thread.sleep(1000); println("two")
}

Jon

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Jon Pretty | @propensive

Chris Toomey

unread,
Dec 4, 2014, 10:01:58 PM12/4/14
to scala...@googlegroups.com, cto...@gmail.com
Indeed it was my bug -- the DB operation in f that I'd thought was synchronous was actually wrapped in another future hence f completed right away while that proceeded asynchronously.

Good to know the world makes sense again :-).

Som Snytt

unread,
Dec 5, 2014, 1:00:32 AM12/5/14
to Chris Toomey, scala-user
To me, a world in which I can't distinguish synchronous from the other kind is a world that doesn't make sense, even if it obeys some internal logic of its own.

I think it was Hamlet who caught the exception with the message, "The time is out of joint."

Chris Toomey

unread,
Dec 5, 2014, 1:54:53 AM12/5/14
to scala...@googlegroups.com, cto...@gmail.com
That's got the makings of a famous quote (in the future).

A lesson from this though is be careful when your async computations return Future[Unit] as you won't get any compiler help in catching situations like mine where the last statement launched an async computation instead of a sync one, which you'd get if it was returning a non-Unit type.

Chris
Reply all
Reply to author
Forward
0 new messages