Singleton and DataSource - java

I'm developing a web application with Java and it needs a connection with a data base. Well administration of resources is very important. The application will be in a Tomcat 6 servlet container, and I've implemented BoneCP to manage connections (I can't use Spring).
I've read that JNDI lookup for DataSource is too much expensive and I'm thinking about creating a singleton of DataSource object, to get the JNDI resource only once, and return the same DataSource for future connections.
Question: Is it a good idea to create a DataSource only once, and get connections from the same DataSource? I don't want to get the same connection, only the same DataSource.
Thank you ;)

Use a pooling datasource, such as is described here:
http://www.javaranch.com/journal/200601/JDBCConnectionPooling.html

Yes, as Renjith suggested, you only need to create the DataSource one time. I actually ran into this same issue yesterday. Every time in my "getConnection" method I noticed I was creating a new InitialContext and DataSource unnecessarily. I revised my Connection Manager class to have a static block of code that creates the DataSource object only when the class gets loaded the first time (after reading BalusC's answer in Proper usage of JDBC Connection Pool (Glassfish))
I thought about using the old-school ServiceLocator pattern (see Pascal's answer in the above link), but I felt it was a bit too overkill for my needs.
Another possibility is that you could also use the #Resource annotation with injection on the DataSources, but that doesn't seem to work with Tomcat 7.

Related

Create Datasource in Code or get it via JNDI from Application Server

In a java application, If we want to use javax.sql.DataSource instead of java.sql.DriverManager to get connections, which approach would be better to create DataSource and WHY?
Create DataSource in the application itself at the application startup time
or
Configure DataSource in the application server and get it via JNDI
Well, it actually depends upon the requirement. You can take this as a general rule.If you have multiple applications and sharing the same DataSource, then it can be a good choice to configure the DataSource in the server. Otherwise, if this is the only application uses the DataSource, then you can have it in the application level itself.

Adavantage of using connection from Data Source over JDBC Driver Manager

Question is basically identify the best practices on data access layer.
I want to choose in between using a data source or traditional driver manager to load the the connection on web applications. I know very clearly following advantages
Flexibility of configuration
In built connection pooling mechanism
But if I can sacrifice advantage of flexibility with configuration and have own connection pooling mechanism, Do I get any other benefit out of data source. In other way around what are limitations or issues I would face while having application managed jdbc driver connection than container managed.
I know the question is so stupid that I should be knowing the advantage of somebody takes care of handling connection than my application. But this is rare scenario where I can't use datasource in web application. I would be looking following things
How better I can design own connection pool my self?
Is there any thing else I should take care when I access connection through DriverManager API
Note that is is very possible to programmatically create a DataSource (backed by a connection pool) dynamically based on user input.
Using Apache Commons-dbcp:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(DATABASE_DRIVER_CLASS);
ds.setUsername(DATABASE_USERNAME);
ds.setPassword(DATABASE_PASSWORD);
ds.setUrl(DATABASE_URL);
ds.setInitialSize(1);
ds.setMaxActive(50);
ds.setDefaultAutoCommit(false);
So I think the question is not really between a DataSource and no-DataSource, but rather between a container managed DataSource and an application managed DataSource.
Container managed DataSources are easier to manage by server-admin types. They can be tuned through the app server web UI, etcApplication managed DataSources do not have this advantage.

Is there any performance difference between these two JDBC Connectivity?

I have used MySqlDataSource for in jdbc connectivity.I have used following code
MysqlDataSource d = new MysqlDataSource();
d.setUser("user");
d.setPassword("pass");
d.setServerName("hostname.com");
d.setDatabaseName("db");
Connection c = d.getConnection();
Also i have searched there is an option of Configuring a MySQL Datasource in Apache Tomcat.
Is there any performance difference between these two? which one is best to use?
Configuring Datasource in tomcat will help you to share same data source between applications running in same tomcat. that Datasource will be managed by container (tomcat in your case).
while the Datasource created in code will be created by your application and can be used by that application only.
So if you have multiple application running on tomcat and accessing same data source, that configuring Datasource in tomcat will be good approach and have performance factor because only one data source is created and not having separate connections for each application
But if you have only single application that the first approach you have used is good one
They both use the internally the same driver, i dont think the performance is much different here, i guess if you need to access teh database only at that place and the enduser isn't supposed to use his own authentication you may use it directly from java, but if you will need the connectivity on different places it could be helpful to configure this using apache configuration, specially that if anything changes like database server, user name or whatever you don't need to get in the code to change it, this could be very important if end users have to set their own configurations.
The improvement of configuring a pool of Connections (as the one provided by tomcat) is mainly that you will actually create and close a lot less of connections.
When using a pool, when you request a Connection to a pool it will look if it has any connection already created and available for reuse and, if it has, it will provide you with it (instead of creating a new Connection, which is a heavy operation). You must still close() a Connection provided by Tomcat so Tomcat knows that it can now reuse when it is requested again.
Additionally, the advantage of the pool is that your code does not need to know the configuration data for the Connection. He just requests a Connection from a given pool and the sysadmin configures it, allowing for greater flexibility (the sysadmin does not need to know how to configure your app, just how to configure the Tomcat which is fairly more standard).

Connection Pooling Strategy For A JSP Site?

I'm doing some work on a JSP site that was coded very badly. For every single database call the original programmer opens and closes a database connection. I'm adding in some new database operations and I would like to do things a little bit better( something like hibernate will come later when more of the site can be rebuilt ). I was thinking of creating a single database connection when a session starts ( after logging in ), storing it in the session object and then closing it in session listener end of session handling function when the session closes. Is this a sound strategy? Thoughts?
I was thinking of creating a single database connection when a session starts ( after logging in ), storing it in the session object and then closing it in session listener end of session handling function when the session closes. Is this a sound strategy? Thoughts?
No. Create a container managed connection pooled data source and get it by JNDI on webapp's startup.
How to create the data source depends on the container in question. In case of for example Tomcat 6.0, you can read it up here: Tomcat JNDI Resources HOW-TO - JDBC Data Sources. In case of for example Glassfish 3, you can do it in the webbased admin console on http://localhost:4848.
Here's how you can finally get it from JNDI:
DataSource dataSource = (DataSource) new InitialContext().lookup(jndiName);
// ...
You can call getConnection() on it. It's sufficient to get the data source only once during webapp's startup, for example in a static initializer block of your database connection manager or perhaps in a ServletContextListener.
The connection should always be acquired and closed in the shortest possible scope. Get it inside the try block where you're executing the query and close it in the finally of the very same try block. Do not keep the connection open longer than necessary. The connection pool will take care about keeping them open, so the performance is already greatly improved that way.
Without commenting on your idea (because I've never done it that way so I don't know for sure), I can say that I've always seen it done something like this (see accepted answer):
How to reuse the same connection with a Spring's JdbcTemplate?
For starters you use a Common DBCP's PoolingDataSource instance stored in your ServletContext (or "application scope" in JSP parlance).
Ideally I would look to migrating to Spring (or Guice or similar).

BasicDataSource configured in spring vs Weblogic datasource

BasicDataSource configured in spring
Weblogic datasource
which implementation is better in terms of
Stability
Performance
scalability
Online Help
I wouldn't even consider using BasicDataSource when using WebLogic Server, its connection pool just rocks:
it's extremely stable, rock solid (one of the top reasons to use it);
it has a great set of features (can't think of any missing one);
it performs very well, no dead lock issues;
it's clusterable;
the administration, configuration are easy and they can be automated with WLST;
monitoring is easy (via JMX);
it's well documented;
it's supported by BEA.
For me, this is a no match.
PS: Of course, this answer applies when running inside WebLogic (which is assumed since the question is about WebLogic connection pool). In your IDE or in a testing context, use whatever you want, e.g. no connection pool at all.
It's much simpler to test and work with Apache's BasicDatasource from your IDE, since you only need the datasource jar file in your classpath. It's not necessary to deploy to an application container.
com.mchange.v2.c3p0.ComboPooledDataSource and the datasource that's bundled with the tcServer is also highly scalable.
The BasicDatasource and the ComboPooledDataSource also gives you the ability to use the same datasource in all environments and it's not coupled to the application container.
And at least the datasource that's bundled with the tcServer is supported by SpringSource.
The ComboPooledDataSource and the Spring alternative are also easy to manage and monitor with JMX.
On the other side, if you're using XA transactions and Weblogic's JTA transaction manager, then you should also use WebLogic's datasource.

Categories

Resources