user1169587
user1169587

Reputation: 1336

Each request from user call a new getConnection()?

The database connection is get like below

public Connection getDBConection(){  
   Context context = new InitialContext();  
   DataSource dataSource = (javax.sql.DataSource) context.lookup("java:myDataSource");  
   Connection conn = dataSource.getConnection();  
}  

For a userA, is each database request should call getDBConnection() once; but no need to control all request use the same connection?

That is, if userA has three database request, then userA should call getDBConnection() three times, and call Connection.closed() after used in each request?

If the userA call getDBConnection() three times (that is, call dataSource.getConnection() three times), is three connection created? Or it is unknown and controlled by weblogic?

I feel very chaos, is it true that there should be one new connection for one database request? or just call DataSource.getConnection() for each database request and the number of new connection created is controlled by web server, no need to think how many connection is actually created.

Upvotes: 2

Views: 4835

Answers (1)

Eric Galluzzo
Eric Galluzzo

Reputation: 3241

Every time you call DataSource.getConnection, the data source will retrieve a connection for you. It should be true that the returned connection is not being actively used by anyone else, but it is not necessarily a brand-new connection.

For example, if you use a connection pool, which is a very common practice, then when you call Connection.close, the connection is not actually closed, but instead returns to a pool of available connections. Then, when you call DataSource.getConnection, the connection pool will see if it has any spare connections lying around that it hasn't already handed out. If so, it will typically test that they haven't gone stale (usually by executing a very quick query against a dummy table). If not, it will return the existing connection to the caller. But if the connection is stale, then the connection pool will retrieve a truly new connection from the underlying database driver, and return that instead.

Typically, connection pools have a maximum number of real connections that they will keep at any one time (say, 50). If your application tries to request more than 50 simultaneous connections, DataSource.getConnection will throw an exception. Or in some implementations, it will block for a while until one becomes available, and then throw an exception after that time expires. For a sample implementation, have a look at Apache Commons DBCP.

Hopefully that answers your question!

Upvotes: 4

Related Questions