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.

This entry was posted in New Features and tagged , . Bookmark the permalink.

4 Responses to ThreadLocal in One Click

  1. These “little” details makes idea the best IDE

  2. anjan bacchu says:

    hi there,

    cool!

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

    BR,
    ~A

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

  4. Niels Harremoes says:

    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?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">