Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap blocking IO in Scala as non blocking

I am using AWS SDK to access files in S3. However, the S3 operations from AWS SDK are synchronous. Is it possible to wrap such synchronous operations to make them asynchronous in Scala?

Wrapping with Future is not a right answer since that operation will block in another thread.

like image 435
Khanetor Avatar asked Oct 25 '25 03:10

Khanetor


1 Answers

Something that I've been using for a while:

import scala.concurrent.{blocking, Future, ExecutionContext}
/**
 * This is an idiomatic way of executing blocking code
 * Use BlockingFuture(...) instead of normal Future(...) anywhere
 */
object BlockingFuture {
    def apply[T](body: => T)(implicit execctx: ExecutionContext): Future[T] = Future { blocking { body } }
}

So, as you said - yes, Futures might block, that's why we use special blocking construct.

More about this:

  • Asynchronous IO in Scala with futures
  • https://groups.google.com/forum/#!searchin/scala-user/future$20blocking/scala-user/LKiVD2PGvew/XDT-UZrAjJcJ
like image 54
sap1ens Avatar answered Oct 26 '25 23:10

sap1ens