ThreadLocal in One Click

Most of applications initially are single threaded, and IntelliJ IDEA was no different; though luckily, now it isn’t — but we had to adapt our code to use multiple threads. In this post I’m going to tell you how.

In our example we see SAXBuilder, which is too expensive to be created every time we need it, so it is stored in a static final field.

Because SAXBuilder is not thread safe, multiple calls to loadDocument from different threads cause a lot of interesting exceptions. This is why we need either to make access to this field synchronized, or to make the field ThreadLocal. In our case, we’re choosing the latter. We encapsulate the field, change its type and initializer, then fix a generated getter. Quite a lot of work, right? Luckily in Maia you can do it all in just one click. Just place caret on a field and press Alt+Enter to smoothly migrate it to ThreadLocal.

Comments below can no longer be edited.

4 Responses to ThreadLocal in One Click

  1. Avatar

    Felipe Cypriano says:

    October 30, 2009

    These “little” details makes idea the best IDE

  2. Avatar

    anjan bacchu says:

    October 30, 2009

    hi there,


    how long before eclipse copies it ? (as it’s been doing for the last 8 years 🙂 )


  3. Avatar

    Markus Jevring says:

    March 1, 2010

    Unfortunately, this wonderful little trick doesn’t work in the Community Edition =(

  4. Avatar

    Niels Harremoes says:

    March 19, 2011

    Sorry to revive an old thread, but I just stumbled upon this. I think this is a very dangerous quickfix, since it introduces a memory leak in an app server environment, where you want your classloaders to be unloadable?

    Threadlocals are implemented as per-thread weak hashmaps. If the value contains a reference to the key, the values will never die, before the thread dies.

    The value in this case is a SAXBuilder instance. This, of course has a reference to the SAXBuilder.class, which has a reference to the classloader for jdom, which has a reference to the JDOMUtil class, which has a reference to the static field, i.e. the ThreadLocal instace. So the loop is tied, and your jdom classloader can now never be garbage collected 🙁

    So IF the initial value in any way references the classloader which loaded the containing class, that classloader will be uncollectable.
    This may or may not be a problem, depending on the use case. But I think it is a bit too dangerous to have as a quickfix?

Discover more