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 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();    


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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.