nus-cs2030 / 2223-s1

MIT License
1 stars 0 forks source link

questions abt lecture 11 #304

Open loberyyq opened 2 years ago

loberyyq commented 2 years ago

how to apply the contents in lecture 11? When do we know to use map or thenDoThis? (coz there is no codecrunch exercise on that so I not sure how to write code abt it)

danqiye1 commented 2 years ago

@loberyyq, don’t get confused by the way the function is named. The thenDoThis method is actually just a map (which means feel free to name it as map). Recall that map are most commonly found in Functor, where a Functor<T> will take in a Function<T,R> in the map method and output a Functor<R>. Can you see that the Async<T> is exactly that Functor<T>?

Now if you study how Async<T> is written, you will notice it is not just any Functor because of its creation spawns a new thread MyThread internally. It also follows that thenDoThis is not just a normal map, because it will spawn a new thread in a newly created Async<R> to apply Function<T,R> only after whatever that Async<T> had been computing in MyThread is done (because of this.join()). Therefore it is better to call this method thenDoThis rather than map, because it waits for the Supplier of this.thread to finish before creating a new Async to compute Function<T,R>.

mohddanesh commented 2 years ago

I think we only use thenDoThis when the question asks you to execute two parts of the code simultaneously, implying asynchronous programming. If not such need, we just use map.