0

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?

Just picture LoginServlet.java doing something like this.

@WebServlet("/LoginServlet.secure")  
public class LoginServletextends HttpServlet {  
    private static final long serialVersionUID = 1L;  

    public LoginServlet() {  
        super();  
    }  

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

}   
user1172490
  • 137
  • 11

1 Answers1

0

I am actually implementing something fairly similar with you have here, and this was how I implemented it: See my answer here

Although there are a few elements in my design that need to be changed based on this answer from BalusC, such as moving my Logger instantiation inside of the doGet, since my Logger is not of a thread-safe design inherently. My DBEngine, however, is designed to support concurrency, and it makes heavy use of PostgresQL's natural row-level-locking.

Sadly, I have not fully completed this project yet, so I cannot tell exactly which pitfalls to avoid, but I will be able to expand this answer in a few months. But this will give you a good idea of the sum of my research on this topic.

Community
  • 1
  • 1
adv
  • 357
  • 5
  • 18