vincent chou vincent chou - 3 months ago 17
Scala Question

Link promise to another

I'm reading scala.concurrent.impl.Promise and am confused by the concept "link DefaultPromise with another". I understand the 'prevent memory leak' part, but don't know how to write an example where the current state of

DefaultPromise
is
DefaultPromise
.

When
DefaultPromise
is first created, its state is
Nil
and the list grows as we keep appending
flatMap
to it. Under what circumstances is the branch

case dp: DefaultPromise[_] => dp.asInstanceOf[DefaultPromise[S]].linkRootOf(p)


in
Future.flatMap
called?

test("default promise linking") {
//f1.getState === Nil
val f1 = Future {Thread.sleep(200000); 2}

//f1.getState === List(CallbackRunner1)
f1.flatMap(x => Future {Thread.sleep(200000); 4})
//f1.getState === List(CallbackRunner2, CallbackRunner1)
f1.flatMap(y => Future {Thread.sleep(200000); 3})

Thread.sleep(30000000)
}

Answer

Take this example:

val f1 = Future {Thread.sleep(200000); 2}
val f2 = f1.flatMap(x => {
    val f3 = Future {Thread.sleep(200000); 4}
    f3
})

f1 and f3 will of course not share the same state - one resolves with 2 the other with 4. But when f1 completes, the handler (f(v)) will create f3 and it will match the case that you are confused about. Then, f2 (p in flatMap) will be linked to f3 so that they share the same state.

Comments