2
\$\begingroup\$

Let's forget about Spring Singleton Beans and about other frameworks in Java. We have one or more simple HttpServlets. And we should make database connection. (doesn't matter what is it, hibernate session factory or JDBC connection). Always I write the following pattern:

class DatabaseService {

    private static DatabaseService instance;

    public static void init() {
        instance = new DatabaseService();
    } 

    public static void destroy() {
        //.. destroy
    }

    public static DatabaseService getInstance() {
        return instance;
    }


    private Connection conn;

    private DatabaseService() {
        conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
    }

    public Connection getConnection() {
        return conn;
    }
}

And every my servlet gets database connection from singleton. But what you think about efficiency that solution? Where I should initialize my DatabaseService singleton? Are there a better solution?

\$\endgroup\$
1
\$\begingroup\$

Like in Spring where you have not defined lazy loading of bean, the singleton beans are created when the context is started up.

3.3.4. Lazily-instantiated beans

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later.

So assuming you have some entrypoint like main() method - there is the best place where you can create singletons etc. main() is basically the beginning of your application and since this method is called you should be able to use DatabaseService.

In my opinion DatabaseService is something like DataSource in spring so it should not be configured as lazy loading.

I would change getInstane to singleton pattern:

public static DatabaseService getInstance() {
    if(instance == null) {
        instance = new DatabaseService();
    }
    return instance;
}

So I will go for:

public static void main(String... args){
    DatabaseService.getInstance() != null ? LOG.info("DatabaseService initialized!") : throw new SystemException("Failed DatabaseService initilization");
    ...
}

or you can use your init method but it would be better to change void to DatabaseService and check whether instance was created successfully.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.