Why assigning instance variable to local variable?

This is something I see in Spring Boot code for example (in the catch block with webServer variable):

@Override
public final void refresh() throws BeansException, IllegalStateException {
    try {
        super.refresh();
    }

    catch (RuntimeException ex) {
        WebServer webServer = this.webServer;
        if (webServer != null) {
            webServer.stop();
        }
        throw ex;
    }
}

Why not just doing this.webServer.stop()?

What is the purpose of local variable webServer?

>Solution :

The main purpose of the assignment is to avoid producing a NullPointerException when the this.webServer is set to null by a concurrent thread after the null-check and before the webServer.stop() call.

That is, without a local variable:

  1. your thread: this.webServer != null -> true
  2. another thread: this.webServer = null
  3. your thread: this.webServer.stop() -> possibly results in NullPointerException (depending on visibility of change in step 2, this might not always happen; a race condition).

In other forms of code, assigning a field to a local variable can also have performance benefits compared to repeatedly referencing a field.

Leave a Reply