I am using HikariCP 2.3.3 with Spring and Jetty 9 and am trying to resolve the fact that when I hot deploy a new war file, all of the Hikari database pool connections to MySQL are left open and idle. I am using a JNDI lookup in my spring applicationContext file to retrieve the datasource from a Jetty context file.
Since I cannot specify a destroy-method in the jndi-lookup like I can if I were to define a dataSource bean, I referred to this question: Should I close JNDI-obtained data source?, where it mentions you can attempt to close the datasource in the contextDestroyed() method of a ServletContextListener. In that case they were using tomcat and c3po so I'm not sure how much the example relates.
I have tried the following in my contextDestroyed method:
InitialContext initial;
DataSource ds;
try
{
initial = new InitialContext();
ds = (DataSource) initial.lookup("jdbc/myDB");
if (ds.getConnection() == null)
{
throw new RuntimeException("Failed to find the JNDI Datasource");
}
HikariDataSource hds = (HikariDataSource) ds;
hds.close();
} catch (NamingException | SQLException ex)
{
Logger.getLogger(SettingsInitializer.class.getName()).log(Level.SEVERE, null, ex);
}
But at HikariDataSource hds = (HikariDataSource) ds; I get the following exception: java.lang.ClassCastException: com.zaxxer.hikari.HikariDataSource cannot be cast to com.zaxxer.hikari.HikariDataSource
I have also tried the following after reading this issue on GitHub: Is it essential to call shutdown() on HikariDataSource?:
InitialContext initial;
DataSource ds;
try
{
initial = new InitialContext();
ds = (DataSource) initial.lookup("jdbc/myDB");
ds.unwrap(HikariDataSource.class).close();
} catch (NamingException | SQLException ex)
{
Logger.getLogger(SettingsInitializer.class.getName()).log(Level.SEVERE, null, ex);
}
But I get the following exception: java.sql.SQLException: Wrapped connection is not an instance of class com.zaxxer.hikari.HikariDataSource
at com.zaxxer.hikari.HikariDataSource.unwrap(HikariDataSource.java:177)
I feel like I'm close to a working solution but can't quite get it. What is the proper way to close a JNDI HikariCP data source, whether in contextDestroyed() or elsewhere?
I can't find where the 2.3.3 code lines up with the HikariDataSource.java:177 line number above. One suggestion is upgrading to the latest HikariCP version, 2.3.8.
While your code looks correct, I suspect that you are running into a classloader issue, whereby the HikariDataSource (class) loaded by Jetty/Spring classloader and registered in JNDI is not the same classloader that is loading HikariDataSource in your web app.
One quick way to check is to log/print both class instances like so:
...
ds = (DataSource) initial.lookup("jdbc/myDB");
logger.info("JNDI HikariDataSource : " + System.identityHashCode(ds.getClass()));
logger.info("Local HikariDataSource: " + System.identityHashCode(HikariDataSource.class));
...
If the two class objects have different hashCodes, they are not the same class. In which case you will have to investigate whether the JNDI instance is registered in the "global JNDI context". If it is, that datasource can be shared across web app instances, and it is not appropriate for your web app to unilaterally shut it down.
UPDATE: Sorry I missed it. Re-reading your question, my guess was correct. Your original error:
java.lang.ClassCastException: com.zaxxer.hikari.HikariDataSource cannot be cast to
com.zaxxer.hikari.HikariDataSource
is a clear indication that there are two classloaders that have loaded two separate instances of the HikariDataSource class. The first is the Jetty classloader (JNDI), and the second is your web application classloader.
This indicates that the pool is shared across web applications and you probably should not try to shut it down from your application context.
Related
I am working on a Java Web Application, and is getting deployed in Websphere Application Server,
I have a class Database.java, which is returning the JDBC Connection with DB2 Database,
jndiName = "jdbc/TestDataSource";
Context ctx = new InitialContext();
envContext = (Context) ctx.lookup("java:comp/env");
javax.sql.DataSource ds = (javax.sql.DataSource) envContext.lookup(jndiName);
conn = ds.getConnection();
and in other classes where am performing operations am creating an object of Database.java class and get the connection and did the jdbc operations, so far it was working fine, but in latest development I have to introduce a thread in servlet class, so the other classes which are doing the operations are running in thread in background and returned the control to servlet immediately. But after implementing this application crashed in Websphere Application Server with below mentioned error, but surprisingly its working perfectly fine Tomcat server.
PFB the Web.xml
<resource-ref>
<description>Connection-ConnectionPool</description>
<res-ref-name>jdbc/TestDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
<mapped-name>jdbc/TestDataSource</mapped-name>
</resource-ref>
Error:
000000e9 SystemOut O Error in NamingException - Database.getConnection(datasource) :- javax.naming.ConfigurationException: A JNDI operation on a "java:" name cannot be completed because the server runtime is not able to associate the operations thread with any J2EE application component. This condition can occur when the JNDI client using the "java:" name is not executed on the thread of a server application request. Make sure that a J2EE application does not execute JNDI operations on "java:" names within static code blocks or in threads created by that J2EE application. Such code does not necessarily run on the thread of a server application request and therefore is not supported by JNDI operations on "java:" names. [Root exception is javax.naming.NameNotFoundException: Name jdbc not found in context "java:comp/env".]
The exception means that the thread which you created doesn't have the context of the Java EE application and thus it cannot know which Java EE component namespace to get java:comp/env/jdbc/TestDataSource from. Note that you can define this same name to mean different things for different Java EE apps/components. There is an easy way around this, which follows Java EE spec standards. Instead of creating your own threads, use a ManagedExecutorService (also part of Java EE) that automatically propagates your application's context to a managed thread, in which case the app server will be able to resolve the lookup properly.
Here is an example:
ExecutorService executor = InitialContext.doLookup("java:comp/DefaultManagedExecutorService");
executor.submit(new Callable<Object>() {
public Object call() throws Exception {
DataSource ds = InitialContext.doLookup("java:comp/env/jdbc/TestDataSource");
Connection conn = ds.getConnection();
try {
// ... do useful stuff with connection
} finally {
conn.close();
}
return result;
}
});
I have implemented HikariCP which is working fine and I'm now planning to do a graceful shutdown of my application and I would like to make HikariCP close the database connection properly and not just killing the java application.
I was reading on google and I could see the HikariDataSource should have a close method.... but in fact I'm not able to see it available:
private static DataSoure ds;
:
public blabla() {
HikariConfig config = new HikariConfig();
config.setJdbc(jdbcURL);
:
ds = new HikariDataSource(config)
In Eclipse, if I tried ds.close()... Eclipse does not showing "close" as a valid method for HikariDataSource:
Am i doing something wrong? Probabily.... Any idea on how to make HikariCP to close properly the database connection?
Thanks,
Helio
You declare ds as javax.sql.DataSource and assign it with HikariDataSource. This way you will not have access to HikariDataSource native method.
((HikariDataSource)ds).close();
would do the trick.
So, I was exploring on how to use connection pooling on java web application. I looked at some tutorials and I am wondering when should I do the context lookup.
Something like this
initContext = new InitialContext();
dataSource = (DataSource) initContext.lookup( "java:/comp/env/jdbc/mysql");
Should it be everytime I get a connection, or should it be a one time thing.
Obviously initialize connection pool one time only, you can do lookup any time required.
Note: The init-context is not creating connection pool
I am trying to use a datasource that I set up on my weblogic server.
datasource JNDI name = thinOracleDataSource
in my code I have the following
public class DAOBean implements java.io.Serializable {
private Connection conn;
public void connect() throws ClassNotFoundException,
SQLException, NamingException {
Context ctx = new InitialContext();
// Lookup using JNDI name.
DataSource ds = (javax.sql.DataSource) ctx.lookup("thinOracleDataSource");
conn = ds.getConnection();
}
But I get this error
javax.naming.NameNotFoundException: While trying to look up /thinOracleDataSource in /app/webapp/PreAssignment2/24911485.; remaining name '/thinOracleDataSource'
am I looking the JNDI name in the right way? or am I missing something? Thanks for any help!!
EDIT:
This is the jndi tree that I can get from the weblogic console
Try naming your datasource jdbc/thisOracleDataSource in Weblogic and reference it as:
DataSource ds = (javax.sql.DataSource) ctx.lookup("jdbc/thinOracleDataSource");
Also, make sure the datasource is "targeted" to your weblogic Java server. All of this can be done in the Weblogic admin console.
Your JNDI key should look like approximately "java:comp/env/jdbc/thinOracleDataSource".
You can verify it by using Weblogic console that allows access (and probably search) in JNDI. So, you can check this manually before writing the code.
This post is intended to be less of a question and more a confirmation that I'm doing things correctly. I've seen many similar posts but I'm not sure I fully understand everything that's been said.
The problem is that, after a certain amount of time, I get an exception when trying to establish a connection to my oracle database. (I'm using Tomcat 6.0 and Spring)
Previously I had the following configuration:
private PoolDataSource poolDataSource = null;
public MainDAOImpl(String url, String username, String password)
throws Exception
{
poolDataSource = PoolDataSourceFactory.getPoolDataSource();
try
{
poolDataSource.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
poolDataSource.setURL(url);
poolDataSource.setUser(username);
poolDataSource.setPassword(password);
}
catch( SQLException e )
{
...
}
}
public List<Object> getValues(String query)
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try
{
connection = poolDataSource.getConnection();
preparedStatement = connection.prepareStatement(query);
...
}
catch( SQLException e )
{
...
}
finally
{
//close connections
}
}
However, sometimes the preparedStatement = connection.prepareStatement(query); threw an SQLException with a "Closed Exception" message.
It's important to note that the MainDAOImpl's constructor gets called only once per server restart (it's dependency injected via Spring).
I've recently changed my setup like so:
private DataSource dataSource = null;
public MainDAOImpl()
throws Exception
{
try
{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/myOracleConn");
}
catch( NamingException e )
{
...
}
}
and poolDataSource.getConnection() to dataSource.getConnection().
I've also added the following Resource to my Context in Tomcat:
<Resource name="jdbc/myOracleConn" auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="<myURL>"
username="<myUsername>" password="<myPassword>"
maxActive="20" maxIdle="10" maxWaith="-1" />
This basically follows http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html word-for-word.
Everything seems to be working. My question is, will these changes solve my closed connection problem or is there something different I need to do?
Thanks,
B.J.
First of all, if you are using Spring for dependency injection, I would recommend that you also use DI to inject the DAO's dependencies into it.
In other words, your DAO should have a DataSource injected into it, rather than the DAO implementation knowing either 1) what type of DataSource to construct or 2) how and where to look it up in JNDI. Spring can handle JNDI lookups for you.
I'd also recommend using Spring's JdbcTemplate, as it makes for a great wrapper over raw JDBC calls yourself.
Finally, the actual exception you are getting may just be because the database server is closing long-open connections. Not sure which connection pool implementation you are using, but in commons-dbcp there is an option for a "validationQuery" which the pool will execute before returning a connection to verify the connection is still valid. I'm sure most other pools supply similar features, which I would recommend here - this way your DAO is never receiving stale connections from the pool.