Syntax : apply() method in Future Class
Here last argument list is an implicit argument list
Example : Executing 3 Threads using Future
Here last argument list is an implicit argument list
def apply[T](body: ⇒ T)(implicit executor: ExecutionContext): Future[T] Starts an asynchronous computation and returns a Future object with the result of that computation. The result becomes available once the asynchronous computation is completed. T the type of the result body the asynchronous computation executor the execution context on which the future is run returns the Future holding the result of the computation
Example : Executing 3 Threads using Future
// PS:39, psn: a15 > a50 scala> import scala.concurrent.Future import scala.concurrent.Future // Import the implicit argument : ExecutionContext scala> import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.ExecutionContext.Implicits.global scala> def threadMethod(threadId : Int) = { | println("Inside thread : " + threadId) | threadId | } threadMethod: (threadId: Int)Int scala> (1 to 3) foreach { threadNo => | // Create Future object. Here apply() Factory method is called | // 1st argument : Asychronous computation | // 2nd argument : Implicit Argument | // : will be used from the import statement of 'ExecutionContext.implicits' | val future = Future { | threadMethod(threadNo) | } | | future onSuccess { | case threadId:Int => println(s"Success : Thread returned : $threadId") | } | future onFailure { | case throwable:Throwable => println(s"Failure : Thread returned : $throwable") | } | } Inside thread : 1 Success : Thread returned : 1 scala> Inside thread : 3 Inside thread : 2 Success : Thread returned : 3 Success : Thread returned : 2
No comments:
Post a Comment