Question regarding concurrency. Imagine 10 different doGet() requests from 10 different users around the world called within milliseconds of each other to a servlet called LoginServlet.java. Inside the servlet's doGet() method is a call to DbUtil.getConnection(). The DBUtil class is static and the method getConnection() is also static. What happens here? What are possible race conditions, concurrent issues, etc etc? Can there be corruption between connections or something? Is there a better alternative to this design for connection pooling?

public class LoginServletextends HttpServlet {  
    private static final long serialVersionUID = 1L;  

    public LoginServlet() {  

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        Connection connection = DbUtil.getConnection();  

This is the static DBUtil class to get connections.

package util;    

import java.sql.Connection;    
import java.sql.SQLException;    

import javax.naming.InitialContext;    
import javax.naming.NamingException;    
import javax.sql.DataSource;    

public class DbUtil {    

    private static DataSource dataSource;    

    static {    
        try {    
            dataSource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/MyDataSource");    
        } catch (NamingException e) {     
            throw new ExceptionInInitializerError("'jdbc/MyDataSource' not found in JNDI");    

    public static Connection getConnection() throws SQLException {    
        return dataSource.getConnection();    


Edited by ~s.o.s~: move to appropriate forum

3 Years
Discussion Span
Last Post by ~s.o.s~

The code would be thread safe if the dataSource.getConnection method is thread-safe. Since the DataSource is just an interface, you'll need to check the specific implementation of the data source you are using (just print out the name of the class) or read the documentation.

I'm assuming your datasource supports pooling otherwise multiple clients can possibly cause this piece of code to become a bottleneck.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.