Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick threadLocalSession vs implicit session

I encountered this problem while posting this question: Slick Write a Simple Table Creation Function

I am very new to Slick and concurrency, knowing only the basics. I worked with JDBC before, but in there you have to manually open a session and then close it. Nothing goes beyond that, and there is very little automation (at least I didn't have to make automated process).

However, I get confused with Slick session. In the tutorial, the example "Getting Started" encourages people to use threadLocalSession:

// Use the implicit threadLocalSession

import Database.threadLocalSession

http://slick.typesafe.com/doc/1.0.0/gettingstarted.html

The original recommendation is:

The only extra import we use is the threadLocalSession. This simplifies the session handling by attaching a session to the current thread so you do not have to pass it around on your own (or at least assign it to an implicit variable).

Well, I researched a bit online, and some people suggest not to use threadLocalSession and only use implicit session. Some suggest using threadLocalSession.

One reason to support implicit session is that "makes sure at compile time that you have a session". Well, I only have two questions:

  1. When people use "thread", are they referring to concurrency? Slick/JDBC data storage was handled through concurrency?

  2. Which way is better? Implicit or threadLocalSession? Or when to use which?

  3. If it is not too much to ask, I read the syntax of {implicit session:Session => ...} somewhere in my Scala book, and I forgot where it was. What's this expression?

like image 538
windweller Avatar asked Dec 21 '13 19:12

windweller


Video Answer


1 Answers

  1. A threadLocalSession is called this way because it is stored in a "thread local variable", local to the current execution thread.

  2. As of Slick 2, we recommend not to use threadLocalSession (which is now called dynamicSession) unless you see a particular need for it and are aware of the disadvantages. threadLocalSession is implicit, too, by the way. The problem is, that a threadLocalSession is only valid at runtime when a withSession (in Slick 2.0 withDynSession) call happened somewhere down the call stack. If it didn't the code still compiles but fails at runtime

  3. {implicit session:Session => ...} is a function from (the explicitly annotated type) Session to ..., where the session is available as an implicit value in ... . In db.withSession{ implicit session:Session => ... }, db creates a session, passes it into the closure handed to withSession. In the closure body ..., the session is implicit and can implicitly used by .list calls, etc.

like image 179
cvogt Avatar answered Oct 23 '22 22:10

cvogt