commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From sinoea kaabi <sin...@msn.com>
Subject Using BasicDataSource as a static class-variable, is it thread safe?
Date Wed, 24 Sep 2008 08:06:10 GMT

Dear all,
I am using the commons-dbcp BasicDataSource with Tomcat 5.5 configured via 
JNDI.

I use a Data class as a datasource manager to retrieve the datasource from a static method.

The datasource (instance of BasicDataSource) is a static class-variable of the Data class.

See Code below:

[code]
public class Data {
 
    private static BasicDataSource ds = null;
   
 
    public static DataSource getDataSource() throws SQLException {
        if (ds == null) {
            try {
                final Context initContext = new InitialContext();
                ds = (BasicDataSource)initContext.lookup("java:/comp/env/jdbc/myDB");
                initContext.close();
                return ds;
            } catch (final NamingException e) {
                e.printStackTrace();
                throw new RuntimeException("Java naming exception when getting connection
from tomcat pool: " + e.getMessage());
            }
        } else {

            return ds;
        }
  }
[/code]

Question:

1. Is it thread safe to have the datasource (ds) as a static class variable

Or if I create a new datasource for each method call as below:

[code]
public class Data {
 
    public static DataSource getDataSource() throws SQLException {

            try {
                final Context initContext = new InitialContext();
                final BasicDataSource ds = (BasicDataSource)initContext.lookup("java:/comp/env/jdbc/myDB");
                initContext.close();
                return ds;
            } catch (final NamingException e) {
                e.printStackTrace();
                throw new RuntimeException("Java naming exception when getting connection
from tomcat pool: " + e.getMessage());
            }

  }
[/code]

Does that mean I am creating a new pool for each method call?

Thanks for any help!
_________________________________________________________________
Win New York holidays with Kellogg’s & Live Search
http://clk.atdmt.com/UKM/go/111354033/direct/01/
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message