The first version of the code should not work. You should not return anything containing a reference to the Session object from the withSession scope. Here you return a closure that contains such a link. When the close is later called by Play, the sSession area is already closed and the Session object is invalid. Admittedly, leaking a Session object in a closure is very easy (and will be caught by Slick in the future).
That's why it seems to work at first, but the leak of Connection: Session objects lazily finds a connection. withSession blocks (or closes) the connection at the end of the block if it was acquired. However, when an unused Session object leaks from the block and is used for the first time after the block is completed, it still lazily opens the connection, but nothing automatically closes it. Some time ago, we recognized this as undesirable behavior, but have not yet corrected it. The fix we have in mind prohibits the Session object from receiving connections after calling their .close method. In your case, this would lead to an exception instead of a leak.
See https://github.com/slick/slick/pull/107
The correct code is indeed the second version you sent, where the returned closure element contains the entire withSession block, not just its result.
cvogt source share