Javalin: Javalin request lifecycle

Created on 19 Dec 2019  路  4Comments  路  Source: tipsy/javalin

Describe your question

Hello! I'm building a small app with javalin and hibernate for database access. I wonder how to best implement database sessions and transactions with javalin. So I wonder how the request lifecycle behaves.

So far I set up a session a and start the transaction in a before handler on *. And I commit my transaction in a after handler on *. The database session is currently bound to the thread. Maybe I'm better off putting it as a ctx attribute?

But this could fail if

  • another request runs on the same thread between my before/route/after flow has finished
  • or if some other before handler happens before my transaction starter
  • or another after handler happens faster my transaction comitter
  • or if the request changes threads on the before/route/after flow
  • or the after handler doesn't get called (am I guaranteed that it will always be called? Even if I get an exception in the route handler?)

Thankful for any pointers or examples!

INFO QUESTION

All 4 comments

I'm not familiar with Hibernate, but I'll attempt to answer the general questions.

another request runs on the same thread between my before/route/after flow has finished

Requests are assigned one thread from the thread-pool, and that thread will only serve that one request. When the request is done, the thread will be released back into the thread-pool.

or if some other before handler happens before my transaction starter

Before-handlers are executed in the order in which they are declared.

or another after handler happens faster my transaction comitter

Same as for before.

or if the request changes threads on the before/route/after flow

It won't :)

or the after handler doesn't get called (am I guaranteed that it will always be called? Even if I get an exception in the route handler?)

It will get called even if there is an exception. It looks roughly like this:

tryBeforeAndEndpointHandlers()
tryErrorHandlers()
tryAfterHandlers()

Hi,

I stumbled upon this for similar reasons as lulzmachine. I'm using jOOQ and investigating how to best handle SQL transactions and toying with the idea of using ThreadLocal based transaction management.

Requests are assigned one thread from the thread-pool, and that thread will only serve that one request. When the request is done, the thread will be released back into the thread-pool.

Does this also apply to async responses / ctx.result(someCompletableFuture)?
I would suspect no, but to be safe?

Does this also apply to async responses / ctx.result(someCompletableFuture)?
I would suspect no, but to be safe?

You're correct, this works differently for async. The thread is released when Javalin is treating the "endpoint" handler (get/post)

Thanks for the quick response!

Was this page helpful?
0 / 5 - 0 ratings