logo
Tags down

shadow

Future onComplete works every other time


By : Craig Moore
Date : September 16 2020, 05:00 AM
this one helps. Your main app thread is probably being terminated before your future completes. Try the following code.
code :
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}

val future = Future {
  Thread.sleep(10)
  10
}

val result = future andThen {
  case Success(value) => println("Here i work")
  case Failure(ex) => println(s"Error: ${ex.getMessage}")
}

println(Await.result(result, Duration.Inf)) // Only if you are sure it will ever finish, still it is recommended to use an appropriate timeout.


Share : facebook icon twitter icon

What's the difference between onComplete and flatMap of Future?


By : Geert
Date : March 29 2020, 07:55 AM
I hope this helps you . When in doubt, follow the types.
onComplete returns Unit, it allows you to do something with the Future result, but it won't return a value
code :
val finalFuture = results
 .flatMap(x => /* do something and return a future */)
 .flatMap(y => /* do something else and return a future */)
 .flatMap(z => /* do something else and return a future */)
 .map(myresult => /* do something */)
 val finalFuture = for {
    x <- results
    y <- /* do something and return a future */
    z <- /* do something and return a future */
 } yield something(z)

Why does Scala's Future.onComplete needs an ExecutionContext


By : x_x
Date : March 29 2020, 07:55 AM
Hope this helps You can provide your own ExecutionContext to onComplete, that will run the code on the same thread:
code :
val immediateContext: ExecutionContext = new ExecutionContext {
  def execute(runnable: Runnable) {
    runnable.run()
  }
  def reportFailure(cause: Throwable) {}
}
val immediateContext: ExecutionContext = new ExecutionContext {
  override def reportFailure(cause: Throwable): Unit = {}
  override def execute(runnable: Runnable): Unit = {
    println("Executing")
    runnable.run()
    println("Executed")
  }
}

def testContext(): Unit = {
  println("Scheduling on an uncompleted future")
  val p = Promise[Int]()
  println("Scheduling")
  p.future.onComplete { _ => println("Completed") }(immediateContext)
  println("Scheduled")
  p.complete(Success(5))

  println()

  println("Scheduling on an already completed future")
  val p2 = Promise[Int]().complete(Success(5))
  println("Scheduling")
  p2.future.map { n =>
    println("Mapping")
    n * 2
  }(immediateContext).onComplete{
    case Success(n) => println(s"Completed: $n") 
    case _ =>
  }(immediateContext)
  println("Scheduled")

  println()

  println("Using scala.concurrent.ExecutionContext.global for comparison")
  val p3 = Promise[Int]().complete(Success(5))
  println("Scheduling")
  p3.future.onComplete {
    _ => println("Completed")
  }(concurrent.ExecutionContext.global)
  println("Scheduled")
}
Scheduling on an uncompleted future
Scheduling
Scheduled
Executing
Completed
Executed

Scheduling on an already completed future
Scheduling
Executing
Mapping
Executed
Executing
Completed: 10
Executed
Scheduled

Using scala.concurrent.ExecutionContext.global for comparison
Scheduling
Scheduled
Completed

In Scala, why is there no implementation for `Future.onComplete`?


By : Xat_MassacrE
Date : March 29 2020, 07:55 AM
This might help you Dig a little deeper. How do you normally create a Future? One way is Future.apply.
What does it do?
code :
 def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)
  def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] = {
    val runnable = new PromiseCompletingRunnable(body)
    executor.prepare.execute(runnable)
    runnable.promise.future
  }

First for-callback prints future list almost every time, second onComplete-callback rarely returns success (never failur


By : Rho
Date : March 29 2020, 07:55 AM
it fixes the issue It's because you have to explicitly block on the future. In your case, the main thread terminates before onComplete completion and sometimes before l foreach .. is finished.
Please add:
code :
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

val listF = l foreach {
  items =>
    for(item <- items) println(s"foreach item : $item")
    println("\n")
}

Await.result(listF, 5 seconds)
l onComplete {
   case Success(i) => println(s"SUCCESS : $i")
   case Failure(i) => println(s"FAILURE : $i")
}

Thread.sleep(3000)

Future onComplete callback is not called


By : bxy
Date : March 29 2020, 07:55 AM
This might help you There is nothing wrong with your logic. Few modifications applied that I suggest you to try out.
code :
import org.slf4j.LoggerFactory

import scala.concurrent.Future
import concurrent.ExecutionContext.Implicits.global
import scala.io.StdIn
import scala.util.{Failure, Success}

object FutureOnComplete extends App {

  private val logger = LoggerFactory.getLogger("test")

  def logElapsedTime[T](f: => Future[T], description: String): Future[T] = {
    val start = System.currentTimeMillis()
    f.onComplete(
      _ =>
        logger.warn(
          s"$description took [${System.currentTimeMillis() - start}]"))
    f
  }

  val f = for {
    _ <- logElapsedTime(Future(1), "1st task to be executed")
    result <- logElapsedTime(Future(2), "2nd task to be executed")
    _ <- logElapsedTime(Future(2), "3rd task to be executed")
    _ <- logElapsedTime(Future(2), "4th task to be executed")
  } yield result

  f.onComplete {
    case Success(v) =>
      logger.info(s"tasks succeeded !!!! $v")
    case Failure(ex) =>
      logger.error(ex.getMessage)
      throw ex
  }

  StdIn.readLine()

}
Related Posts Related Posts :
  • scala: check if a prime number using a while loop
  • scala: sum of squares of every even-positioned digits starting from 2nd position
  • scala: any built-in function to divide a double by another double and return quotient and remainder as a tuple
  • How do I extract each words from a text file in scala
  • In Scala, why it is impossible to infer TypeTag from type alias or dependent type?
  • Join two spark Dataframe using the nested column and update one of the columns
  • How to create shared JDBC connection to use on executors?
  • Need to deserialize the .toString representation of a complex Map[String, AnyRef] object
  • Covariant safe cast in Scala
  • Scala dynamic return type based on input type
  • Useful stack traces for futures/parallel code
  • Achive dynamic string interpolation in Scala spark?
  • Testing Play framework controller that streams responses
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk