Software Programmer
asked on
Log4j MDC variable or thread local variable
Hi,
I want to share a few variable and values across layers - Presentation, Business, Persistence layer for HttpRequest - i.e single thread application where the app is deployed in tomcat
Is log4J MDC should be used or thread local variable would be the right choice?
Thanks.
I want to share a few variable and values across layers - Presentation, Business, Persistence layer for HttpRequest - i.e single thread application where the app is deployed in tomcat
Is log4J MDC should be used or thread local variable would be the right choice?
Thanks.
ASKER
Assume we are not using MDC library in a project and want to have a thread local variable by ourself to propagate the values. Can u show me an example how a thread local variable can be initialized and used via code ??? One code snippet would be fine
You can do something like this:
Initialisation:
Set a value when the user logs in:
Access the value when you need it:
Remove the value when the user logs out:
Initialisation:
public static final ThreadLocal<String> USERNAME = new ThreadLocal<>();
Set a value when the user logs in:
USERNAME.set("ausername");
Access the value when you need it:
USERNAME.get();
Remove the value when the user logs out:
USERNAME.remove();
ASKER
How about following this link - https://stackoverflow.com/questions/24329474/accessing-session-variables-outside-servlet ???
The above code just talks about initializing for each class..
Let me know about the above link, so that will use the same if that is correct.
The above code just talks about initializing for each class..
Let me know about the above link, so that will use the same if that is correct.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
With regards to the thread local, I think the MDC implementations do use ThreadLocal, so you could go with just MDC.
Just make sure that you clean the values in the MDC when the requests ends, otherwise you will end up with loads of unused data (which will not be eligible for gc).