Question

I'm new at the web develope and I have a small problem. I'm using scala akka with spray to make a website. My leader give me a question : I have a response like this

case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => {
    Thread.sleep(10)
    sender ! HttpResponse(entity = "this is t2")
}

the Thread.sleep(10) is represent a heavy thread with constanst processing time is 10ms, so it make the whole program run slower 1000times, so how do I make it retrieve 10times more HTTPRequest ? The hint was using actors but somehow I read the whole documents but still missing something

Was it helpful?

Solution

One way to do it:

case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => {
    val replyTo = sender
    Future {
      someCPUIntensiveFunction()
      replyTo ! HttpResponse(entity = "this is t2")
    }
}

Basically, you move the "heavy function" call into a Future. That will make the current thread, which receives the HttpRequest, proceed as soon as it creates the future, and is able to process the next HttpRequest. The future will execute its code in a separate thread. So, you'll have two "paths" in your program. One, which will process HttpRequest, and another which will execute someCPUIntensiveFunction()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top