Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use same database transaction in separate thread with Play Framework 2.2

From play's documentation:

Because of the way Play 2.0 works, the action code must be as fast as possible (ie. non blocking). So what should we return as result if we are not yet able to generate it? The response is a promise of result!

So I shouldn't be doing database calls directly inside of the action. This now confuses me when I look at Plays JPA documentation:

Every JPA call must be done in a transaction so, to enable JPA for a particular action, annotate it with @play.db.jpa.Transactional. This will compose your action method with a JPA Action that manages the transaction for you

This leaves me a little bit confused. If I follow the documentation, I shouldn't block an action thread with a database call. But if the action is what's creating and managing the database transaction, aren't I losing that transaction by sending the work to an actor, or somehow offloading the work to another thread? I mean, I'm new to scala and play, but I just don't see how the transaction would follow into separate threads. Does anyone have an explanation, or a way that I should be doing this? I'm very confused.

like image 833
spierce7 Avatar asked Nov 02 '22 02:11

spierce7


1 Answers

You are missing a piece of the puzzle, read under "Highly synchronous" here: http://www.playframework.com/documentation/2.2.x/ThreadPools

So, yes, you would want it to be non-blocking but if you cannot have that because of JPA/JDBC etc. then you can configure play like you would with the regular Java web containers - a thread pool with lots of threads. It won't give you all that play can give but it might very well be good enough for you.

You could also create a specific thread pool/execution context and run the JPA/JDBC stuff only on that and keep the rest of your server non blocking.

like image 155
johanandren Avatar answered Nov 15 '22 10:11

johanandren