Showing posts with label async. Show all posts
Showing posts with label async. Show all posts

Thursday, 25 July 2019

java async task



.map

jshell> var t1 = CompletableFuture.completedFuture(100)
t1 ==> java.util.concurrent.CompletableFuture@25f38edc[Completed normally]

jshell> var t2 = t1.thenApply(x -> x * 2)
t2 ==> java.util.concurrent.CompletableFuture@1a86f2f1[Completed normally]

jshell> t2.get()
$14 ==> 200

.fmap

jshell> var t1 = CompletableFuture.completedFuture(100)
t1 ==> java.util.concurrent.CompletableFuture@506c589e[Completed normally]

jshell> var t2 = CompletableFuture.completedFuture(200)
t2 ==> java.util.concurrent.CompletableFuture@69d0a921[Completed normally]

jshell> var result = t1.thenCompose($ -> t2)
result ==> java.util.concurrent.CompletableFuture@7aec35a[Completed normally]

jshell> result.get()
$19 ==> 200

javascript equivalent

> var t1 = Promise.resolve(100)
undefined
> var t2 = t1.then(x => x * 2)
undefined
> t2
Promise {
  200,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }


Sunday, 27 December 2015

Scala Future with play framework


Async controller
----------------------------
package beard.controllers

import play.api.mvc._
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.libs.Json._
import reactivemongo.bson._
import service.BeardService
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.concurrent.Future
import scala.util.{Failure, Success, Random}

class AsyncBeardController extends Controller {

 def sayAsyncBeard = Action.async { request =>
    val futureResult = Future {
      intensiveComputation()
    }
    futureResult.map(result =>
      Ok(result)
    )
  }


def intensiveComputation(): JsObject = {
      Thread.sleep(Random.nextInt(5000))
        Json.obj("value" -> "beard")
  }
}

Test
-------
$ curl -XGET http://localhost:9000/sayAsyncBeard
{"value":"beard"}

You will get the response after ~5seconds.