Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading