Concurrent Programming Languages
Lab 12: Scala I
We love donuts. Therefore, we want to know how many donuts our preferred shop has in stock and buy them if possible. We want to automate this.
Question 1
Assume the shop provides some sort of web service telling how many donuts of a certain variety are available. To simulate this, write a Method which takes a flavour as input and return a Future[Int]. Implement that the method returns a randon integer if a valid flavour is supplied and throws an Exception otherwise. You can hardcode a list of valid flavours for this (e. g. chocolate, vanilla, plain).
Question 2
Use the method to ask in parallel for the stocks of two valid and one invalid flavour. Print the results once it is available. For comprehension is an option to do the parallel tasks. Look at this post for a nice explanation.
Note that it turns out the for comprehension only returns a failure if one of the Futures fails. So the combination of valid and invalid is not possible.
Question 3
Write a method to buy a certain quantity of donuts of a certain flavour. The method should return a Future boolean, true if the flavour is valid and the number of donuts is in stock, false otherwise. You can use the method from 1) in this method.
Question 4
Now write a program which, after having asked for the stock of donuts, buys all available donuts. There are several options how this could be done. Think about what options are possible and their use. Have a look at the stackoverflow post for sequential execution. If you order the number of donuts available, is there a guarantee (assuming there are other customers of the shop) that you can buy the quantity you want to buy?