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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With