|By Patson Luk||
|August 31, 2013 11:00 AM EDT||
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||
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:
Thread 2 (the instance)'s field ThreadLocalMap (m2) has 1 entry:
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!
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||
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.
An IoT product’s log files speak volumes about what’s happening with your products in the field, pinpointing current and potential issues, and enabling you to predict failures and save millions of dollars in inventory. But until recently, no one knew how to listen. In his session at @ThingsExpo, Dan Gettens, Chief Research Officer at OnProcess, discussed recent research by Massachusetts Institute of Technology and OnProcess Technology, where MIT created a new, breakthrough analytics model for ...
Dec. 8, 2016 10:30 AM EST Reads: 520
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life sett...
Dec. 8, 2016 10:30 AM EST Reads: 7,292
Successful digital transformation requires new organizational competencies and capabilities. Research tells us that the biggest impediment to successful transformation is human; consequently, the biggest enabler is a properly skilled and empowered workforce. In the digital age, new individual and collective competencies are required. In his session at 19th Cloud Expo, Bob Newhouse, CEO and founder of Agilitiv, drew together recent research and lessons learned from emerging and established compa...
Dec. 8, 2016 10:00 AM EST Reads: 978
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
Dec. 8, 2016 09:45 AM EST Reads: 1,917
Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe...
Dec. 8, 2016 09:30 AM EST Reads: 590
DevOps is being widely accepted (if not fully adopted) as essential in enterprise IT. But as Enterprise DevOps gains maturity, expands scope, and increases velocity, the need for data-driven decisions across teams becomes more acute. DevOps teams in any modern business must wrangle the ‘digital exhaust’ from the delivery toolchain, "pervasive" and "cognitive" computing, APIs and services, mobile devices and applications, the Internet of Things, and now even blockchain. In this power panel at @...
Dec. 8, 2016 09:15 AM EST Reads: 928
Extracting business value from Internet of Things (IoT) data doesn’t happen overnight. There are several requirements that must be satisfied, including IoT device enablement, data analysis, real-time detection of complex events and automated orchestration of actions. Unfortunately, too many companies fall short in achieving their business goals by implementing incomplete solutions or not focusing on tangible use cases. In his general session at @ThingsExpo, Dave McCarthy, Director of Products...
Dec. 8, 2016 08:45 AM EST Reads: 887
SYS-CON Events has announced today that Roger Strukhoff has been named conference chair of Cloud Expo and @ThingsExpo 2017 New York. The 20th Cloud Expo and 7th @ThingsExpo will take place on June 6-8, 2017, at the Javits Center in New York City, NY. "The Internet of Things brings trillions of dollars of opportunity to developers and enterprise IT, no matter how you measure it," stated Roger Strukhoff. "More importantly, it leverages the power of devices and the Internet to enable us all to im...
Dec. 8, 2016 08:30 AM EST Reads: 830
Businesses and business units of all sizes can benefit from cloud computing, but many don't want the cost, performance and security concerns of public cloud nor the complexity of building their own private clouds. Today, some cloud vendors are using artificial intelligence (AI) to simplify cloud deployment and management. In his session at 20th Cloud Expo, Ajay Gulati, Co-founder and CEO of ZeroStack, will discuss how AI can simplify cloud operations. He will cover the following topics: why clou...
Dec. 8, 2016 08:30 AM EST Reads: 968
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo 2016 in New York. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place June 6-8, 2017, at the Javits Center in New York City, New York, is co-located with 20th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry p...
Dec. 8, 2016 08:15 AM EST Reads: 2,038
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, will share examples from a wide range of industries – includin...
Dec. 8, 2016 07:00 AM EST Reads: 1,716
"We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 8, 2016 06:30 AM EST Reads: 1,140
Internet of @ThingsExpo has announced today that Chris Matthieu has been named tech chair of Internet of @ThingsExpo 2017 New York The 7th Internet of @ThingsExpo will take place on June 6-8, 2017, at the Javits Center in New York City, New York. Chris Matthieu is the co-founder and CTO of Octoblu, a revolutionary real-time IoT platform recently acquired by Citrix. Octoblu connects things, systems, people and clouds to a global mesh network allowing users to automate and control design flo...
Dec. 8, 2016 04:30 AM EST Reads: 748
With 15% of enterprises adopting a hybrid IT strategy, you need to set a plan to integrate hybrid cloud throughout your infrastructure. In his session at 18th Cloud Expo, Steven Dreher, Director of Solutions Architecture at Green House Data, discussed how to plan for shifting resource requirements, overcome challenges, and implement hybrid IT alongside your existing data center assets. Highlights included anticipating workload, cost and resource calculations, integrating services on both sides...
Dec. 8, 2016 04:00 AM EST Reads: 3,807
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 8, 2016 04:00 AM EST Reads: 1,063
Unless your company can spend a lot of money on new technology, re-engineering your environment and hiring a comprehensive cybersecurity team, you will most likely move to the cloud or seek external service partnerships. In his session at 18th Cloud Expo, Darren Guccione, CEO of Keeper Security, revealed what you need to know when it comes to encryption in the cloud.
Dec. 8, 2016 04:00 AM EST Reads: 4,821
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.
Dec. 8, 2016 02:45 AM EST Reads: 1,311
The WebRTC Summit New York, to be held June 6-8, 2017, at the Javits Center in New York City, NY, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 20th International Cloud Expo and @ThingsExpo. WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web co...
Dec. 8, 2016 01:45 AM EST Reads: 1,417
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dec. 8, 2016 12:30 AM EST Reads: 1,156
The Internet of Things (IoT) promises to simplify and streamline our lives by automating routine tasks that distract us from our goals. This promise is based on the ubiquitous deployment of smart, connected devices that link everything from industrial control systems to automobiles to refrigerators. Unfortunately, comparatively few of the devices currently deployed have been developed with an eye toward security, and as the DDoS attacks of late October 2016 have demonstrated, this oversight can ...
Dec. 8, 2016 12:15 AM EST Reads: 1,390