Tag Archives: Threads

Know the JVM Series – 4 – Thread Locals

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

What’s harder, synchronizing 2 threads or synchronizing 1000 threads?

Recently, I came across an interesting presentation by Paul Tyma (Senior Engineer at Google / CEO at ManyBrain Inc), regarding the performance of Java NIO vs classic IO APIs. The presentation was titled as ‘Thousands of Threads and Blocking I/O – The old way to write Java Servers is New again (and way better)‘. The title itself sounds downright interesting, and it was worth reading (learned a lot from it). I highly recommend this presentation to any Java programmer. You can download the slides from here.

However, the reason for this blog post is not the presentation itself. Rather, this blog post is about a question that Pual raises (tagging it as ‘Interview question’), that many people will answer wrong, because the answer that comes to mind looking at the surface is misleading.

What’s harder, synchronizing 2 threads or synchronizing 1000 threads?

Continue reading