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.

image description