I have already read the interesting discussion on following SO thread about ThreadLocal and its use.
- When and how should I use a ThreadLocal variable?
- Purpose of ThreadLocal?
- How does ThreadLocal usage reduce reusability
- Is it OK to use ThreadLocal for storing the requested Locale?
This questions is more towards a design time choice. My scenario is like this
If I have a value object in a web application that may need to used inside same thread by almost all steps. I can think of two interface design options like below
Approach #1 Using Method Parameter Passing.
I have so far focused on coming up with a interface that can have methods with parameters of a value object interface.
For example:
public interface SomeDataProcessorInterface {
public void processSomething(SomeValueObjectInterface vo);
}
public interface SomeValueObjectInterface extends Serializable {}
Aproach #2 Using ThreadLocal
In this approach I can have a interface with no method parameter and just create a static class to access my value objects using a threadlocal.
For example:
public interface SomeDataProcessorInterface {
public void processSomething();
}
public interface SomeValueObjectInterface extends Serializable {}
public Class StaticClass {
private static ThreadLocal<SomeValueObjectInterface> threadLocalVO = new ThreadLocal<SomeValueObjectInterface>();
public static ThreadLocal getThreadLocal() {
return threadLocal;
}
Which approach is better? and why?
Which one of these implementation is going to have less chances of memory leak?
Which one of these implementation is going to be good for Java Garbage Collector?
I read thru some of the points in other thread however I am still not clear which approach is better if I am starting from scratch.