Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database connections for servlet threads? [duplicate]

With regards to servlets being multithreaded by default, does each servlet instantiate a database connection or is the connection shared between all threads of that servlet?

I am using JDBC as an interface between my servlet and an Oracle database.

If a database connection is shared between all threads, does this mean that I should use connection pooling to the database?

/** Open the connection here **/
public void init() {
    String url = "server";
    String username = "pwd";
    String password = "usr";
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        conn = DriverManager.getConnection(url, username, password);
    } catch (Exception e) {
        System.err.println("Error making pool: " + e);
        conn = null;
    }
}
like image 870
tomaytotomato Avatar asked Jan 20 '26 20:01

tomaytotomato


2 Answers

If a database connection is shared between all threads , does this mean I should use connection pooling to the database?

Yes, definitely! JDBC connections and single-threaded and not thread-safe. Just introduce connection pool in between, fetch connection first and close it as soon as you can during the same request.

like image 183
Tomasz Nurkiewicz Avatar answered Jan 22 '26 10:01

Tomasz Nurkiewicz


Depending on how you write your Connection, it can be per-servlet (instance variable) or global (static variable - providing you are not in a cluster environment and you manage concurrency, which would be a severe bottleneck)

However, if you want to make your system efficient, reliable, scalable, more easily mantainable and not having to implement more advanced feature such as reconnect in case of a link failure (which I think is the case considering your backend is Oracle) you should look into your application server connection pooling mechanisms.

like image 29
thedayofcondor Avatar answered Jan 22 '26 10:01

thedayofcondor