sid-ramakrishnan / ScoreOverFlow

0 stars 0 forks source link

Incorrect lazy initialization of static fields #4

Open Debug1995 opened 5 years ago

Debug1995 commented 5 years ago

Ex: ReservationDaoFactory.java[lines 15-18]

public static ReservationDao getInstance() throws DBConnectionException {
    if (dao == null) {
        try {
            EntityManager manager =           DaoFactory.factory.createEntityManager();
            dao = new ReservationDao(manager);
        } catch (ServiceException e) {
            // Unable to connect to database
            throw new DBConnectionException(e);
        }
    }
    return dao;
}

Spotbugs Explanation: This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model website.

Our Analysis: This method tries to connect with the database, which may raise some problems when called by multiple threads. To make the code robust, volatile keyword should be used.