Link to home
Start Free TrialLog in
Avatar of Software Programmer
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.
Avatar of girionis
girionis
Flag of Greece image

The MDC is automatically accessible from everywhere. But it is not accessible if you are using internal thread pools or Executors. For thread pools you will need to create your own thread pool, like it is explained here: https://stackoverflow.com/questions/6073019/how-to-use-mdc-with-thread-pools#19329668

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).
Avatar of Software Programmer
Software Programmer

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:
public static final ThreadLocal<String> USERNAME = new ThreadLocal<>();

Open in new window


Set a value when the user logs in:
USERNAME.set("ausername");

Open in new window


Access the value when you need it:
USERNAME.get();

Open in new window


Remove the value when the user logs out:
USERNAME.remove();

Open in new window

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.
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial