Wednesday, March 2, 2011

Getting objects created in current java thread

There are two ways to resolve object dependency in java e.g. objects created in one method will be needed in other method in the same thread request. One way of resolving this dependency is that you pass newly created objects as parameter to method but this approach has drawback e.g. if you have created an object in one method, then that method is calling another which is calling another method and that method requires object created in first method then using first approach you will have to pass object in the parameter of second method and then second method will pass it to third method as parameter. As second method does not require it but we will have to pass it to resolve dependency of third method.
Second and most efficient approach is using ThreadLocal class. You can set object in first method to this class by this:
Now in third method you can get this object using this:
Usually this approach is used with objects which are current request's context related e.g. FacesContext object is the key object in JSF and is required to use it anywhere in the request. so JSF creates instance of FacesContext in each request and set it to ThreadLocal. and then later on returns it from ThreadLocal.

No comments:

Post a Comment