1

I am using below code snippet to create a singleton instance of Connection object for a web application which will be used by multiple users.

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

This class will return same instance of connection until and unless connection is closed or null. I suppose same connection will be shared by all users on different machine as it is static one.

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

4

2 回答 2

1

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

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 所说,连接池是一个更好的工具。很可能您的网络服务器已经提供了它们,如果没有的话,还有第三方库。

于 2013-02-19T07:21:30.500 回答
0

这是否会通过限制其他用户的连接以禁用自动提交来给其他用户带来问题

是的。

如果一个用户使用了 con.commit() 或者通过中途提交他们的交易?

是的。

数据库连接对于多线程使用是不安全的,通常甚至不应该是成员字段,更不用说单例了。它们应该是方法局部变量。如果你想节省创建和销毁它们,你必须使用连接池。

于 2013-02-19T22:32:00.967 回答