7

Is it recommended to use ThreadLocal to store a Thread Context?

I am building a backend server application where there are typical services that I need to run.

Note: We are not building this over a SOA architecture.

Before the start of each service I need to give it a state which has some Service Contex which is variable map to work up on. This variable map is shared when services are running parallelly.

Now for example a service needs to check weather it has to be halted or timed-out based on some thread related parameters.

Question: Is it a good approach to keep the thread context inside thread local and then building api's over service context to access parameters over these variables.

This would help me to hide the complex behavior and it wouldn't open up my internal things.

Thanks, Aditya

Aditya
  • 71
  • 1

2 Answers2

1

It looks like your server application framework ought to provide you with the means to implement this functionality in a simpler way - unless you are implementing your own framework.

Now for example a service needs to check weather it has to be halted or timed-out based on some thread related parameters.

An EJB container provides this kind of functionality. EJBs also provides a session context and the means to ensure that the context can be restored if execution is transferred between threads (by passivation + activation).

richj
  • 7,499
  • 3
  • 32
  • 50
  • I am building my own framework and thats exactly where I am facing design questions. Since its a back-end server app I wont have sessions as well and My initial point of view was that my services should typically work up on a memory heap(context) only but to handle such thread paradigms and such other closely coupled operations My orchestrator designs and the services are getting closely tied which I want to avoid. – Aditya Jan 17 '11 at 11:26
  • There are some very high quality open source frameworks available (JBoss, Spring, Glassfish, Tomcat). I would probably start by looking at some of those to see how they deal with the problem. – richj Jan 17 '11 at 20:40
0

You can use ThreadLocal quite freely but you must define your thread model cleanly (see if you have any control on the thread creation)... also keep in mind that assuring the state stored in the ThreadLocal might not what you expect, if you are relying on any clean-up code.

Also: do use (cant stress more) WeakReference for anything that your code is not directly responsible.

bestsss
  • 11,796
  • 3
  • 53
  • 63