Recurring Revenue Authors: Zakia Bouachraoui, Pat Romanski, Yeshim Deniz, Elizabeth White, Xenia von Wedel

Related Topics: Java IoT, Industrial IoT, Microservices Expo, Open Source Cloud, Machine Learning , Recurring Revenue

Java IoT: Blog Post

A Painless Introduction to Java’s ThreadLocal Storage

Best practices for using another powerful class: ThreadLocal from java.lang

In my last blog, we explored WeakHashMap which is based by WeakReference in Java. Now let's look at some best practices for using another powerful class: ThreadLocal from java.lang, which is also implemented using WeakReference.

What is ThreadLocal? A simple example
As its name suggests, a single instance of ThreadLocal can store different values for each thread independently. Therefore, the value stored in a ThreadLocal instance is specific (local) to the current running Thread, any other code logic running on the same thread will see the same value, but not the values set on the same instance by other threads. (There are exceptions, like InhertiableThreadLocal, which inherits parent thread's values by default.)

Let's consider this example:

We have a TransactionManager class that provide static methods to:

  • Start a transaction with a generated ID
  • Store that ID as a static field and provide a transaction ID getter method to other code logic that needs to know the current transaction ID.

In a single threaded environment, TransactionManager can simply store the ID as a static field and return as is. However, this will certainly not work in a multiple-threaded environment. Imagine multiple threads are using TransactionManager - transaction IDs generated by each thread can overwrite each other as there is only one static instance of transaction ID. One may synchronize and block other transactions to avoid overwrites, but this would totally defeat the purpose of having multiple threads.

In order to solve this problem, ThreadLocal provides a very neat solution:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class TransactionManager { private static final ThreadLocal<String> context = new ThreadLocal<String>(); public static void startTransaction() { //logic to start a transaction //... context.set(generatedId); } public static String getTransactionId() { return context.get(); } public static void endTransaction() { //logic to end a transaction //... context.remove(); } }

Different thread that starts transactions via TransactionManager will get its own transaction ID stored in the context. Any logic within the same thread can call getTransactionId() later on to retrieve the value belongs/local to that Thread. So problem's solved!

The Internals of ThreadLocal and How it Works

Let's drill down a little bit into the ThreadLocal's internals. ThreadLocal is implemented by having a Map (a ThreadLocalMap) as field (with WeakReference entry) within each Thread instance. (There are actually 2 maps; the second one is used for InheritabeleThreadLocal, but let's not complicate the picture). The keys of those maps are the corresponding ThreadLocals themselves. Therefore, when a set/get is called on a ThreadLocal, it looks at the current thread, find the map, and look up the value with "this" ThreadLocal instance.

Still confused? I certainly am. Let's look at a real example.

  • Code running in Thread 1 calls set() on ThreadLocal instance "A" with value "123″
  • Code running in Thread 2 calls set() on ThreadLocal instance "A" with value "234″
  • Code running in Thread 1 calls set() on ThreadLocal instance "B" with value "345″

And this is the end result:

Thread 1 (the instance)'s field ThreadLocalMap (m1) has 2 entries:

ThreadLocal A "123″
ThreadLocal B "345″

Thread 2 (the instance)'s field ThreadLocalMap (m2) has 1 entry:

ThreadLocal A "234″

Now if some code logic in Thread 1 calls get() on ThreadLocal instance "A", the ThreadLocal logic will lookup the current Thread, which is instance Thread 1, then access the field ThreadLocalMap of that Thread instance, which is m1, it can then lookup the value by using m1.get(this), with "this" as ThreadLocal and the result is "123″

Now what to watch out for!
Did I hear weak reference for ThreadLocal entries? Does that mean I don't have to clean up? Well, it's not quite that simple.

First of all, the value object put into the ThreadLocal would not purge itself (garbage collected) if there are no more Strong references to it. Instead, the Weak reference is done on the thread instance, which means Java garbage collection would clean up the ThreadLocal map if the thread itself is not strongly referenced elsewhere.

So now the question is: when would the Thread object get garbage collected?

The answer is: it depends, but always assume the thread is long running. 2 common examples:

  • Servlets. The threads that handle servlet requests usually stay alive in the container for the lifetime of the server instance. Code logic that uses ThreadLocal might be referenced indirectly by servlets.
  • Thread pooling java.util.concurrent.Executors. Java encourages recycling threads!

A typical usage of Executor introduced in Java 1.5, if ThreadLocal maps are not cleaned up properly after a transaction is done, next TransactionProcessingTask might inherit values from another previous unrelated task!

1 2 ExecutorService service = Executors.newFixedThreadPool(10); service.submit(new TransactionProcessingTask());

Be careful with initialization of ThreadLocal, below is an implementation of a counter by Thread. Can you tell what is wrong in the below initialzation?

1 2 3 4 5 6 7 8 9 10 11 12 public class Counter { private static ThreadLocal<Integer> counter = new ThreadLocal<Integer>(); static { counter.set(0); } public int getCountInThread() { return counter.get(); } //.... }

The counter would not get initialized correctly! Though the counter is declared as static, it CANNOT be initialized by having a static initializer, as the initializer only runs once when the first thread references the Counter class. When the second thread comes in, it does not run counter.set(0) on that thread, therefore counter.get() returns null instead of 0! One solution is to sublcass ThreadLocal and override the initialValue() method to assign non-null initial value.

With these in mind, you can probably picture the consequences of not cleaning up after ourselves! An operation that runs on a recycled thread might inherit the values from previous operation on the same thread! Besides, it can also cause memory leaks as the instance stored in ThreadLocal will never get garbage collected if the thread is alive.

As a rule of thumb, always clean up/reset your threadlocal after you have finished your "unit of operation"! Even though the current code might be simple enough to bypass the cleanups, it might be adapted and integrated into servlets/thread pooling later on! After all, cleaning up responsibly is always appreciated both in the realms of programming and real life.

More Stories By Patson Luk

A Java developer who has spent the better part of the last decade working on financial services applications with companies from HSBC to Mobilearth and Parasoft, Patson is experienced in various aspects of computer systems, from large scale enterprise banking system to lightweight mobile payment solutions. He now leads Java instrumentation and tool development for the TraceView product at AppNeta. Patson's focus is on using java bytecode manipulation technologies to gain greater visibility into the full spectrum of Java based technologies. This includes higher level application frameworks from Spring and Struts to Webflow, AppServers from TomCat to JBoss, and Databases from MySQL to Oracle. He's also writes frequently on the AppNeta blog - www.appneta.com/blog

IoT & Smart Cities Stories
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...
Rafay enables developers to automate the distribution, operations, cross-region scaling and lifecycle management of containerized microservices across public and private clouds, and service provider networks. Rafay's platform is built around foundational elements that together deliver an optimal abstraction layer across disparate infrastructure, making it easy for developers to scale and operate applications across any number of locations or regions. Consumed as a service, Rafay's platform elimi...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
In today's enterprise, digital transformation represents organizational change even more so than technology change, as customer preferences and behavior drive end-to-end transformation across lines of business as well as IT. To capitalize on the ubiquitous disruption driving this transformation, companies must be able to innovate at an increasingly rapid pace.
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Ca...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.