Make c3p0 behave like Hibernate built-in connection pool - java

Probably this is stupid or weird question but I'm facing a strange bug in the app for many weeks and do not know how to solve it.
There are some Quartz jobs that periodically updating database (change the status of orders and stuff). There is only Hibernate 3.1.3 without spring and all transactions handled in code manually with explicit call session.close() in finally block.
It all worked fine with Hibernate built-in connection pool, however after I have changed built-in connection pool to c3p0 pool there are some bugs appeared connected with database transaction/session management. There is no exceptions or anything in the log files, so it is hard to tell what exactly was the reason.
Is there any way to make c3p0 connection pool behave like built-in pool by configuration? I need only one c3p0 feature - checking dead connections. Before this pool was implemented there was idle SQL Connection Reset issue. To keep connections alive I decided to use c3p0 pooling instead of built-in.
here is my current c3p0 configuration:
c3p0.min_size=0
c3p0.max_size=100
c3p0.max_statements=0
c3p0.idle_test_period=600
c3p0.testConnectionOnCheckout=true
c3p0.preferredTestQuery=select 1 from dual
c3p0.autoCommitOnClose=true
c3p0.checkoutTimeout=120000
c3p0.acquireIncrement=2
c3p0.privilegeSpawnedThreads=true
c3p0.numHelperThreads=8
Thanks in advance.
c3p0 is an old version: 0.9.0.4, because I have Java 1.4 environment.
Here is a rough example how transactions are managed by the code:
SessionFactory sessionFactory = null;
Context ctx = null;
Object obj = null;
ctx = new InitialContext();
obj = ctx.lookup("HibernateSessionFactory");
sessionFactory = (SessionFactory) obj;
session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// some transactional code
if (!tx.wasRolledBack() && !tx.wasCommitted()) {
tx.commit();
}
} catch (Exception ex) {
if (tx != null && !tx.wasRolledBack() && !tx.wasCommitted()) {
// if it is runtime exception then rollback
if (ex instanceof RuntimeException) {
logger.log(Level.ERROR, "10001", ex);
try {
tx.rollback();
} catch (RuntimeException rtex) {
logger.log(Level.ERROR, "10002", rtex);
}
}
else {
// attempt to commit if there are any other exceptions
try {
tx.commit();
} catch (RuntimeException rtex) {
logger.log(Level.ERROR, "10004", rtex);
// if commit fails then try to rollback
try {
tx.rollback();
} catch (RuntimeException rtex2) {
logger.log(Level.ERROR, "10002", rtex2);
}
// then rethrow this exception
throw rtex;
}
}
}
finally {
session.close();
}

Related

Why JPA/Hibernate transaction is active even when I did not start one explicitly

My problem is that JPA/Hibernate returns true for a call of entityManager.getTransaction().isActive() even when I did not explicitly start a transaction (see code below).
The problem here is that I want to read something from the database and a SerializationException is ok in this scenario, because this just indicates that the persisted object does not fit to the actual code any more and needs to be recalculated. Instead of just returning null the code below throws the following exception:
Transaction rollback failed.
org.hibernate.TransactionException: Unable to rollback against JDBC Connection
This shows me, there must have been a transaction somewhere which I did not start in my code. The finally block in the code above is
final EntityManager entityManager = Persistence.createEntityManagerFactory("test").createEntityManager();
try {
final TypedQuery<Test> query = entityManager.createQuery("SELECT t FROM test t", Test.class);
return query.getResultList();
} catch (final PersistenceException e) {
if (e.getCause() instanceof SerializationException) {
LOG.debug("Implementation changed meanwhile. That's ok - we return null.");
return null;
}
throw e;
} finally {
EntityManagerCloser.closeEntityManager(entityManager);
}
And the EntityManagerCloser looks like this:
public final class EntityManagerCloser {
private static final Logger LOG = LoggerFactory.getLogger(EntityManagerCloser.class);
public static void closeEntityManager(EntityManager entityManager) {
if (entityManager.getTransaction().isActive()) {
try {
entityManager.getTransaction().rollback();
} catch (PersistenceException | IllegalStateException e) {
LOG.error("Transaction rollback failed.", e);
}
}
if (entityManager.isOpen()) {
try {
entityManager.close();
} catch (IllegalStateException e) {
LOG.error("Closing entity manager failed.", e);
}
}
}
}
Hibernate docs says "Always use clear transaction boundaries, even for read-only operations". So do I really need to insert a
entityManager.getTransaction().begin();
....
<do read here>
....
entityManager.getTransaction().commit();
around every read operation I perform on the database?
I could implement another closeEntityManager method for read-only operations without the rollback transaction block but I want to understand why there IS a transaction at all. Thanks for any help!
The problem is that when you call entityManager.getTransaction(); a new transaction object will be created. So it is better to save the transaction reference to a variable as shown below.
Transaction txn = entityManager.getTransaction();
if (txn.isActive()) {
try {
txn.rollback();
} catch (PersistenceException | IllegalStateException e) {
LOG.error("Transaction rollback failed.", e);
}
}
Thanks to Jobin I quickly found the solution to my problem:
I think I need to call entityManager.isJoinedToTransaction() in my closeEntityManager method before calling entityManager.getTransaction().isActive().
This will prevent the EntityManagerCloser to start its own transaction which I can not rollback later because I did not explicitly call transaction.begin() on it.

JPA multithreaded inserts

I am using MS SQL Server, and my program recently started losing the DB connection randomly. I am using a non-XA driver.
The most likely suspect is the asynchronous database logging I added.
The sneaky thing is, I have used a thread pool:
ExecutorService ruleLoggingExecutor = Executors.newFixedThreadPool(10);
and in the finally block of my process, I start off a new thread that calls down to the addLogs() method.
The code works for hours, days, and then during a totally unrelated query, it will lose the DB connection. I have an inkling that the problem is that two concurrent inserts are being attempted. But I don't know if putting 'synchronized' on the addLogs method would fix it, or if I need transactional code, or what. Any advice?
In the DAO:
private EntityManager getEntityManager(InitialContext context) {
try {
if (emf == null) {
emf = (EntityManagerFactory) context
.lookup("java:jboss/persistence/db");
}
return emf.createEntityManager();
} catch (Exception e) {
logger.error(
"Error finding EntityManagerFactory in JNDI: "
+ e.getMessage(), e);
return null;
}
}
public void addLogs(InitialContext context, String key, String logs,
String responseXml) {
EntityManager em = getEntityManager(context);
try {
TblRuleLog log = new TblRuleLog();
log.setAuthKey(key);
log.setLogMessage(logs);
log.setDateTime(new Timestamp(new Date().getTime()));
log.setResponseXml(responseXml);
em.persist(log);
em.flush();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
em.close();
}
}
It seems the connection is closed after a timeout, perhaps due to transaction not being commited/rolled back (and locks not being released on the tables/rows).
Manual flushing looks suspicious. I'd use entityManager.getTransaction().begin/commit() and remove em.flush().

Hibernate org.hibernate.TransactionException: nested transactions not supported on jaxrs

I am using jersey with mysql and hibernate 4 and c3p0. I have created a initialization servlet that configures hibernate and sets the current session context class to thread.
I have created hibernateUtils class that contains static methods for getting and committing sessions and I am using a filter to start a session on inbound request and commit it upon response.
The problem is that at some random intervals I am getting org.hibernate.TransactionException: nested transactions not supported exception, but I am not trying to create a new session except on the filter.
Correct me if I am wrong but when setting the current session class to thread I don't need to create a threadlocal in the hibernateutil, hibernate does this. So my question is, is this a safe way to handle that and what could cause the error happening on random intervals?
====================== EDIT ===========================
Sorry for not posting the code earlier.
So the filter implements the ContainerRequestFilter,ContainerResponseFilter
in the request filter I am doing
Session session = sessionfactory.getCurrentSession();
session.getTransaction().begin();
session.setDefaultReadOnly(readOnly);
and in the response
Transaction transaction = sessionfactory.getCurrentSession().getTransaction();
try {
if (transaction != null && !transaction.wasCommitted()
&& !transaction.wasRolledBack() && transaction.isActive()) {
transaction.commit();
}
} catch (HibernateException e) {
Transaction transaction = sessionfactory.getCurrentSession().getTransaction();
try {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
} catch (HibernateException e) {
} finally {
Session session = sessionfactory.getCurrentSession();
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (HibernateException e) {
log.error("Closing session after rollback error: ", e);
throw e;
}
}
It seems that you are using programmatic transaction demarcation in your filter (as far as I understood). So please double check that you terminate properly each transaction, nevermind what append during the request (i.e. rollback if you get an exception and commit otherwise) :
try {
session.getTransaction().begin();
// call the filter chain
session.getTransaction().commit()
}
catch (RuntimeException e) {
session.getTransaction().rollback();
}
Without the code it's difficult to be sure, but I guess that for some request you didn't terminate the transaction properly (i.e. by a commit or by a rollback). So the transaction remains associated to the thread and the thread go back to the thread pool (in a very strange state since there is still a transaction associated with it), then another request reuse the same thread, a new transaction is created in the filter... and you got the exception.
EDIT
After looking carrefully at your code, it (may) confirms my assumptions.
Look at the flow when transaction.wasRolledBack()==true : it won't be commited nor rolled back.
And if you the javadoc for Transaction.wasRolledBack() :
Was this transaction rolled back or set to rollback only?
If the transaction is marked as "RollBack only" : it will return true, but it don't means that the transaction is ended. It means that the only possible ending state for the transaction is "RollBack".
But, on the other hand the same javadoc also say this:
Returns: boolean True if the transaction was rolled back via this local transaction; false otherwise.
I found that ambiguous.
So I suggest you to do this:
if (transaction != null && !transaction.wasCommitted()
&& !transaction.wasRolledBack() && transaction.isActive()) {
transaction.commit();
}else if(transaction.wasRolledBack()){
transaction.rollback();
}

Hibernate: Do you need to manually close with sessionFactory?

I have way too many threads being used. I keep running out of memory in my unit tests. Do I need to close my session if I'm using sessionFactory. Won't the commit below end the session?
Session session = sessionFactory.getCurrentSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
transaction.commit();
}
catch (Exception e)
{
if (transaction != null)
{
transaction.rollback();
throw e;
}
}
finally
{
//Is this close necessary?
session.close();
}
No, it won't end the session. One session can span any number of transactions. Close the session explicitly. BTW such things are clearly documented.
In yout catch, verify if the transaction isActive() too.

Reload web server with gwt and c3p0 connection pool?

I have a web application written in gwt, and I'm using a PostgreSQL database in the back end. When I make a new session on the server, I set up c3p0 and get a jdbc connection:
ComboPooledDataSource source = new ComboPooledDataSource();
Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");
source.setProperties(connectionProps);
source.setJdbcUrl("some jdbc url that works");
and when I close my session on the server, I close the ComboPooledDataSource.
However... when I press the yellow "reload web server" button in GWT development mode and refresh my page, I get the following warning, and a bunch of subsequent errors preventing me from obtaining a database connection:
WARNING: A C3P0Registry mbean is already registered. This probably means that an application using c3p0 was undeployed, but not all PooledDataSources were closed prior to undeployment. This may lead to resource leaks over time. Please take care to close all PooledDataSources.
Which I assume means that reloading the web server didn't close the ComboPooledDataSource I made (probably a safe assumption). Is there any way I can get it to do that so I can obtain a connection after reloading the web server?
Closing dataSource generally (not only C3P0) is unadvisable because they should to be used from many applications on your server. If you kill this connection pool other can loose data access. In practice you shoud leave pool management to your container and use only JNDI.
Anyway if you neet to ged rid of the warning in your GWT console use this method in your EventListener contextDestroyer:
public abstract class YourListenerimplements EventListener {
//Probably you initialize your dataSource here. I do it with Guice.
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
...
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
connection = dataSource.getConnection(); //Your dataSource (I obtain it from Guice)
} catch (SQLException ex) {
} finally {
try {
if (connection != null) {
connection.close();
}
if (dataSource != null) {
try {
DataSources.destroy(dataSource);
dataSource = null;
} catch (Exception e) {
}
}
} catch (SQLException sQLException) {
XLog.error(sQLException);
}
}
}
}

Categories