Logging is a mechanism of keeping track of the runtime behavior of an application, mainly for debugging / tracing purposes. In almost all of significantly complex / vital applications, maintaining a proper application log is a must; hence, almost all developers are quite familiar with the paradigm of logging. And it isn’t rocket science. You just have to call a simple method with whatever you want to log, and mess around with a simple configuration file, and that’s all. So what’s the big deal?
The problem is that though logging is a simple thing to do, doing it correctly needs a lot of practice, experience and understanding. That makes it more of an art than a science. In my personal experience, mastering the art of logging requires lots of patience, experience and forward thinking. It’s quite difficult to teach someone how to do it (sort of tacit knowledge), and most freshers tend to see the effort put into writing to log files as something additional. But all that effort pays up when you go through long nights trying to figure out what went wrong in a production system. But for that, it is important that proper logging is done through-out the system, which requires all of the team to master this dark art. Just one guy doing it right in a team is simply not enough.
Thread Local Storage (TLS) is a special construct in multi-threaded programming, which allows to associate a variable with a particular thread. This is different from normal variables, which are associated with a process. In other words, a normal variable will be shared by threads of a same process (in procedural programming terms). However, a Thread Local variable has a copy of it per thread, and modifications by a particular thread is applicable for code running inside that thread only.
With the inherent multi-threaded nature of most enterprise Java applications, having some understanding about Thread Local variables are useful to solve some problems which would otherwise be difficult. We’ll start our discussion by looking into a practical problem that is faced by JEE applications, so that we have a good understanding about the power Thread Locals.
Consider a web based JEE application, which consists of JSP/Servlet based presentation tier, EJB based service facade tier, and business logic implemented in POJOs, and finally Hibernate in the persistence tier. In this application, users are required to authenticate before using secured parts of the application, and we will be using the standard JAAS to facilitate this. Assume that in our POJO based Business Logic classes and Hibernate DAOs, we need to obtain the currently logged in users ID for auditing purposes. How can we solve this problem? Continue reading