June 18, 2019
Hot Topics:

Threads Versus The Singleton Pattern

  • May 31, 2007
  • By Rob Lybarger
  • Send Email »
  • More Articles »

Problem Resolution: The Updated ThreadLocal Singleton Factory

Instead of storing a "static Helper" instance variable in the factory class, instead store a "static ThreadLocal" instance variable in the factory class, and arrange (via override) to return a Helper object from its get() method:
public class HelperFactory {

   private static ThreadLocal instance = new ThreadLocal() {
      protected Helper initialValue() {
         return new Helper();

   public static Helper getHelper() {
      return instance.get();

That is everything you need: declaration of a static ThreadLocal object with an override of its initialValue() method. Note also how the static factory getter method now delegates to the ThreadLocal object's get() method. Run the demo code a few more times. Although the exact statement order will still be somewhat mixed, both threads will accomplish their respective objects successfully:

threadB: Helper has state 0
threadB: Beginning operation finished.
threadA: Helper has state 0
threadA: Beginning operation finished.
threadB: Helper has state 1
threadB: Middle operation finished.
threadA: Helper has state 1
threadA: Middle operation finished.
threadB: Helper has state 2
threadB: End operation finished.
Code section finished.
threadA: Helper has state 2
threadA: End operation finished.
Code section finished.


To wrap up, you can, with the slightest amount of work, be more forward-thinking in the design of your singleton factory classes. You might not be working on a multi-threaded application now, but a quick turn of the fate of your use cases or requirements might force it into existence later—long after you've forgotten about the operational details in the factory class. Relatedly, it is easy to get so involved in the details and business logic of JDBC code for a J2EE web application that you forget how each request is likely processed by a separate thread. (This could turn into an interestingly stressful debug session, as it'll more likely bite customers on site than developers in house.) A common pattern is to create some sort of helper object to do a lot of the common-place heavy lifting associated with JDBC calls. Other similar situations might arise in a multi-threaded network service utility. The ThreadLocal-based solution is a simple and effective solution that you should definitely keep in your mental toolbox.

Page 3 of 3

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date