1
votes

In this example an Execution Context is used to process the future.

Why is this used when Scalike has a built in connection pool?

Shouldn't the Future use one of the pool threads to execute? It seems like a real waste to ForkJoin a thread just to wait on the Future while another thread does the IO work.

http://scalikejdbc.org/documentation/transaction.html

object FutureDB {
  implicit val ec = myOwnExecutorContext
  def updateFirstName(id: Int, firstName: String)(implicit session: DBSession): Future[Int] = {
    Future { 
      blocking {
        session.update("update users set first_name = ? where id = ?", firstName, id)
      } 
    }
  }
  def updateLastName(id: Int, lastName: String)(implicit session: DBSession): Future[Int] = {
    Future { 
      blocking {
        session.update("update users set last_name = ? where id = ?", lastName, id)
      } 
    }
  }
}

object Example {
  import FutureDB._
  val fResult = DB futureLocalTx { implicit s =>  
    updateFirstName(3, "John").map(_ => updateLastName(3, "Smith"))
  }
}

Example.fResult.foreach(println(_))
1

1 Answers

4
votes

Why is this used when Scalike has a built in connection pool?

A connection pool is not a thread pool. A connection pool is simply a collection of open database connections kept by some object that handles opening, closing, and provisioning them to other APIs. Connection pools generally know nothing of threads. You can have a connection pool with 50 open connections in it, but if your application only has one thread, you will only be able to use one at a time (with a blocking API like this), as executing a query through a connection will block whatever thread called it.

An ExecutionContext is required so that you can provide your own thread pool, in any way you want. That could mean the default context scala.concurrent.ExecutionContext.Implicit.global, a fixed thread pool, or fork join pool of your own creation, etc. This allows you to tune your application based on your performance needs, without being tied down to a single ExecutionContext.