Does SQL block blocking in the Play Framework?

I probably misunderstand something fundamental in the Play Framework (2.x), but both the documentation on accessing a regular SQL database and project samples do this asynchronously.

No Promise<Result> , no Akka materials, etc.

Do you block the main server thread if you execute a database query, for example, a regular MySQL JDBC driver? What am I missing?

+4
source share
2 answers

AFAIK, if you look at the “computer-database” pattern, you are absolutely right, it blocks the main thread, since actions are not performed asynchronously.

Here is an excerpt from the sample :

 public static Result list(int page, String sortBy, String order, String filter) { return ok( list.render( Computer.page(page, 10, sortBy, order, filter), sortBy, order, filter ) ); } 

Here Computer.page() makes some blocking JDBC calls.

If you want to do this asynchronously, you must enclose the database call in an async(F.Promise<Result>) call async(F.Promise<Result>) . Something like that:

 public static Result list(int page, String sortBy, String order, String filter) { return async( Akka.future( new Callable<Result>() { public Result call() { return ok( list.render( Computer.page(page, 10, sortBy, order, filter), sortBy, order, filter ) ); } } ) ); 

}

+3
source

Yes, the db driver blocks a thread waiting for results from the database.

Even if you end the JDBC call in the future Akka, as ico_ekito suggests, it will still block one server thread during the entire database query time. Doing this potentially only makes the call in another thread (depending on how Akka decides to execute it), but it still blocks this thread.

The only suitable way is to use a non-blocking database driver.

Btw, you can easily detect a blocking db driver. If its interface looks something like this:

 ResultSet results = connection.execute(query); 

It definitely blocks. You can recognize non-blocking APIs by methods that return Futures, Promises (which are futures with the record side) or accept callbacks.

Also note that there is no “main” server thread (for example, the user interface thread in browsers / desktop applications). There are only a few thread processing requests.

For a deeper discussion, see here .

+3
source

All Articles