java - 连接对象的单例实例是否会在 Web 应用程序中产生问题

标签 java jdbc connection singleton

我使用下面的代码片段为将由多个用户使用的 Web 应用程序创建 Connection 对象的单例实例。

static {
        try {
            String driver = PropertyReader.getPropertyReader("driverClassName");        
            Class.forName(driver).newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

   private static Connection conn = null;
private static synchronized Connection getDBConnection()
    {
         try{
             if(conn == null || conn.isClosed()){
                conn = null;
                String URL = PropertyReader.getPropertyReader("url");
                String userName = PropertyReader.getPropertyReader("username");
                String password = PropertyReader.getPropertyReader("password");
                conn = DriverManager.getConnection(URL,userName,password);
                logger.info("Preparing Connection..."); 
             }               
             else{
                 logger.info("Returning already prepared connection..");
             }
         }

         catch(Exception e)
         {
             e.printStackTrace();
         }

         return conn;
    }

此类将返回相同的连接实例,直到连接关闭或为 null。 我想相同的连接将由不同计算机上的所有用户共享,因为它是静态的。

如果一个用户将自动提交设置为关闭以将几个语句作为事务提交,这是否会通过限制其他用户的连接以禁用自动提交或在一个用户使用了 con.commit() 的情况下中途提交其事务来给其他用户带来问题?

最佳答案

是的,这会引起问题。他们共享同一个实例,所以这个说法是错误的

If one user is setting auto commit to off to commit couple of statements as transaction, will this create problems for other users by restricting their connection to disable autocommit as well or by commiting their transaction in mid way if one user has used con.commit()? 

应该是这样的

If one user is setting auto commit to off to commit couple of statements as transaction, will this create problems for other users because the connection they are sharing has been set to not autocommit and all of their statements will now become part of the new transaction**

由于所有用户(线程)都使用同一实例,因此一个用户对其所做的更改将影响其他用户。

正如 Shivam Kalra 所说,连接池是一个更好的工具。您的网络服务器很可能已经提供它们,如果没有,则有第三方库。

关于java - 连接对象的单例实例是否会在 Web 应用程序中产生问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14951651/

相关文章:

php - 什么设置可能导致 AMP 服务器对每个浏览器一次只允许 1 个请求?

C 套接字 : problem with connect() and/or accept() between clients. 111:连接被拒绝

java - 如何使用正则表达式检查连接泄漏?

java - J2ME,逐行处理永无休止的http连接

java - 在Java中将余弦/正弦转换为角度

java - 从 JNDI 连接池检索的数据库连接设置

java - 多重更新仅适用于 jdbc 中的查询之一

java - 将 JDBC Type 3 驱动程序与 Java 1.6 结合使用

java - JAXB 是否可以将两个或多个元素编码到一个域对象字段中?

java - ModelAndView中重新发送请求参数