0
votes

In my Application I create a session using a session factory. when I perform this checking, the FindBug show me a warning that "sessionFactory is null guaranteed to be dereferenced". How to solve this?

  if (!sessionFactory.isClosed()) {
            session.close();
            sessionFactory.close();
       }
2
Please post whole code. See findbugs.sourceforge.net/… - m4rtin

2 Answers

2
votes

The whole code will probally looks something like this

SessionFactory sessionFactory = null;
Session session = null;

try{
    do some stuff
catch(Exception e){

} finally {
  if (!sessionFactory.isClosed()) {
            session.close();
            sessionFactory.close();
       }
}

Findbugs sees that your variables are null to begin with, and if there is an exception in your try block, the variables might not have been initialized. Thus it gives an error. Its solved easy by adding null checks:

  if (sessionFactory!= null && !sessionFactory.isClosed()) {
            if(session != null){
             session.close();
            }
            sessionFactory.close();
       }
0
votes

Findbug shows that

There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions).

Possible scenario/use case/cases are like this.

1.) When branching is present in the code and we suppose to initialize object in branch and accessing that object(without null check) out of the branch.

As user3227602 shows a code, You have declared sessionFactory object as NULL object and initialize it in a try-catch-finally block.

Imagine a scenario that before initializing, if exception occurs(due to some processing) then flow will come in catch - finally block. So sessionFactory still only declared as a NULL object. So Null check is advisable.

2.) When some statement (if-elseif-else) is present in the code and we suppose to initialize object in that block(if block, elseif block or in else block) and accessing that object(without null check).

if(condition1)
{
       //blah blah
       sessionFactory = new Configuration().configure().buildSessionFactory();
       //blah blah
}
else
{
       //blah blah
}
if (!sessionFactory.isClosed()) {
       session.close();
       sessionFactory.close();
}

If result of the condition1 is false then your sessionFactory object will never initilize. so NULL check is required for this.