A
A
ak40u2012-08-27 11:18:06
Java
ak40u, 2012-08-27 11:18:06

What is the best way to make an object to work with the database: put the link in a static variable or recreate it?

What is the best way to make an object for working with the database: put the reference in a static variable or recreate it every time you need it?

Example:

public class Test {
    static DB db = new DB();
    
    public static void main(String[] args){
        //some code
        db.sendRequest();
    }
    
    private static void someMethod(){
        //come code
        db.sendRequest();   
    }
}


OR

public class Test {
    public static void main(String[] args){
        //some code
        new DB().sendRequest();
    }

    private static void someMethod(){
        //come code
        new DB().sendRequest();
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
1
1nd1go, 2012-08-27
@1nd1go

It depends on what DB is. If it itself manages shared access to blocking resources (connections there, etc.), and at the same time is not itself a blocking or other bottle neck, then you can make it a Singleton (well, or a static field).
It is also worth taking into account the cost of creating such an object.

L
LeoCcoder, 2012-08-27
@LeoCcoder

you need to read the documentation for the DB class and do as it is written there. Or:
1. if this is your self-written class, then only you understand how best to do it.
2. If you write everything in one thread and the DB works synchronously, then it will not matter how many DB you create, create one static and user.
3. if the creation of several DB instances will somehow increase the performance of your application and you VERY NEED IT, then you need to think. Perhaps it will be necessary to make a pool, as already advised. If you provide documentation for the DB class and database configuration, then I think I can help with really practical advice, not theory.
P.S. Not all database queries can be executed in parallel. Even if you keep several connections to the database, it can still execute all queries sequentially. You need to look at the documentation for the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question