![scala future scala future](https://image.slidesharecdn.com/futurepromises-150724181714-lva1-app6891/95/scala-future-promises-45-638.jpg)
However there are even more powerful tools in our box. This feels pretty much like ListenableFuture but with cleaner syntax. omURL(new URL(""), StandardCharsets.UTF_8.name()).mkStringĬase Success(html) => ("Result: " + html)Ĭase Failure(ex) => logger.error("Problem", ex) More in a spirit of ListenableFuture from Guava we will register some completion callbacks first: I am not even mentioning about blocking and waiting for them synchronously (but examine official documentation if you really need it).
![scala future scala future](https://eu.cdn.autosonshow.tv/4701/capitolskoda/CK69XEL/SKODA__SCALA__SE_L_TSI_DSG__PETROL__GREY__2020__CK69XEL-02_md.jpg)
Having Future instance we would like to process the result. In next examples I assume some implicit context is available. Finally you can of course pass ExecutionContext explicitly. If you are inside an actor you can reuse Akka dispatcher to run your task using the same thread pool as actors use. Notice how implicit val is picked up automatically.
SCALA FUTURE FULL
You have full control over the number of threads and their behaviour. Second approach takes existing ExecutorService and wraps it. Use this context only for small applications as it doesn't scale well and is quite inflexible. Implicit val ec = omExecutorService(Executors.newFixedThreadPool(50))įirst approach uses built in execution context composed of as many threads as many CPU/cores you have. ExecutionContext is just like ExecutorService but can be given implicitly.
SCALA FUTURE CODE
By now you should be wondering, how do you configure threads running this task? Good question, this code won't compile as it stands, it needs ExecutionContext to work on. Provided code block will be executed asynchronously later and future (of Future type) represents a handle to the value of that block. That was quick! future is of inferred type. New URL(""), StandardCharsets.UTF_8.name() We will continue our web crawler example taking yet another approach, this time with Akka on top of Scala. To fully appreciate the latter advantage check out scala.Option Cheat Sheet if you haven't yet grasped monads in practice in Scala.
![scala future scala future](https://image.slidesharecdn.com/forkjoinpool-150514082233-lva1-app6892/95/how-does-scalas-future-work-3-638.jpg)
Moreover futures in Akka are special for two reasons: Scala syntax together with type inference greatly improve readability and monadic nature. You typically never block waiting for a response, instead you send a message and expect response to arrive some time in the future. Shouldn't come a surprise that concept of a future is ubiquitous in a system like that. Akka is actor based, event-driven framework for building highly concurrent, reliable applications.