nam
nam

Reputation: 3632

Future and infinite loop in Scala

I want to execute 2 independent infinite loops in scala. The first task takes about 1 second for each run and the second takes 0.5 seconds.

Here is the code:

package future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object MyFuture {
  def task1(): Future[Unit] = Future {
    println("doing job 1")
    Thread.sleep(1000)
  }

  def task2(): Future[Unit] = Future {
    println("doing job 2")
    Thread.sleep(500)
  }

  def infiniteLoop(): Future[Unit] = {
    Future.sequence(List(task1(), task2())).flatMap(x => infiniteLoop())
  }

  def main(args: Array[String]): Unit = {

    Await.ready(infiniteLoop(), Duration.Inf)
  }

}

The output of the program

doing job 1
doing job 2
doing job 2
doing job 1
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2

I want the output of the job 2 to be twice as the output of job 1 because it takes half the time.

What I can do to simulate 2 real independent process?

Upvotes: 2

Views: 3755

Answers (1)

vitalii
vitalii

Reputation: 3365

Consider using either java's scheduled executor to schedule tasks with fixed interval. Or you can use Akka if you need communication between this tasks. BTW this code does what you ask:

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

/**
  * Created by hibou on 13/02/16.
  */
object MyFuture {
  def task1(): Future[Unit] = Future {
    println("doing job 1")
    Thread.sleep(1000)
  }

  def task2(): Future[Unit] = Future {
    println("doing job 2")
    Thread.sleep(500)
  }

  def loopTask1(): Future[Unit] = {
    task1.flatMap(_ => loopTask1())
  }

   def loopTask2(): Future[Unit] = {
    task2.flatMap(_ => loopTask2())
  }

  def infiniteLoop(): Future[Unit] = {
    Future.sequence(List(loopTask1(), loopTask2())).map(_ => ())
  }

  def main(args: Array[String]): Unit = {

    Await.ready(infiniteLoop(), Duration.Inf)
  }


}

Upvotes: 3

Related Questions