3

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;
    }
}
Regent
  • 5,142
  • 3
  • 21
  • 35
tomaytotomato
  • 3,788
  • 16
  • 64
  • 119

2 Answers2

4

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

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.

thedayofcondor
  • 3,860
  • 1
  • 19
  • 28