2

consider this bit of code:

public void foo(){
       try{
        //some cool statements here
      }
      finally {
         if(session != null){
             session.close();
             sesssion = null;
          }
     }
   }

Since the session is closed, is the value assigned to session going to make sense? Please provide some valuable insights.

  • It's generally useless. It could be done to tell the GC that `session` is ready to be collected, but you have no control over the GC. Also, if your method ends after the `finally` block session will be `null` anyway. – BackSlash Sep 03 '18 at 13:05
  • Is there any case like "session deletion race condition" in Java where setting it to null may be helpful? https://developer.joomla.org/news/738-more-details-about-the-session-deletion-race-condition.html – alwaysabeginner Sep 03 '18 at 18:01

2 Answers2

0

Setting local variable to null is unnecessary, to wit, it's part of CERT Oracle Secure Coding Standard's Recommendations

Setting local reference variables to null to "help the garbage collector" is unnecessary. It adds clutter to the code and can make maintenance difficult. Java just-in-time compilers (JITs) can perform an equivalent liveness analysis, and most implementations do so.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

Setting variables to null can be useful in scenarios where the objects themselves have become useless, in this example a closed session. Such objects usually document that after calling close or a similar method, all further operations on that object will fail, e.g. by throwing IllegalStateException. In those cases it arguably makes sense to erase such an instance, especially if other parts of the code expect and check for a null instance as a sign of "no connection".

As stated in other answers, garbace collection however is not a valid reason to set a variable to null.

Felk
  • 7,720
  • 2
  • 35
  • 65