tags:

views:

517

answers:

3

I trying to understand the best prastice of using ThreadLocal for the above questions. From my understanding the reason of using this is to ensure only one session/pm created for entire application. My question is

  1. is there any impact of using threadlocal like this on clustering application? (example google app engine) ?

  2. if u use "transactional" begin,commit on my application, i do not need to use threadlocal right? since "transaction" already ensure my session open and close properly?

  3. if i need to use "transactional", tx, it should be in threadlocal as well?

  4. why not just use "static" instead of "threadlocal" ?

i interested to hear feedback from you all regarding advantages/disadvantages of using this techinque?

+3  A: 
  1. Probably not unless your clustering software can migrate threads between nodes. In this case, you'd need to migrate the thread local data as well.

  2. No. The transaction is attached to the session, so you must keep both in sync. While you can begin a transaction in thread A and commit it in thread B, it's usually very hard to make sure that this work reliably. Therefore: Don't.

  3. Yes.

  4. static is global for the whole application. threadlocal is global per Thread.

Conclusion: If you're a beginner in this area, I suggest to use Spring. The Spring Framework solves many of the problems for you and helps you with useful error messages when something breaks.

Follow the documentation to the letter, especially when it doesn't make sense. Chances are that you missed something important and the Spring guys are right.

Aaron Digulla
Agreed. Likewise, if you have "new Connection()" anywhere in your code, you're doing it wrong. Use Spring to abstract all the nitty-gritty away.
trenton
+1  A: 

ThreadLocal is not used to create one session for the whole application. It is used to create one session for every thread. Every user session will be one thread so the ThreadLocal ensures that every user accessing you web page/ database will get its own database connection. If you use a static singleton pattern every user on the server will use the same database connection and I don't know how that would work out.

Janusz
A: 

The implementation of many of the Transaction engines is actually using ThreadLocal to associate the session state you have with the database to a particular thread. This makes for instance running multiple threads inside of a transaction very difficult.

ThreadLocal is a guarantee of Thread safety but queryable in a semi static way later on by another piece of code. Its a thread global variable. This makes it useful for temporary but session aware information. Another use beyond transactions might be holding onto internal parameters for Authorisation which are then checked with a proxy.

Paul Keeble