Skip site navigation (1) Skip section navigation (2)

Re: Connection exceptions

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: Thomas Finneid <tfinneid(at)fcon(dot)no>
Cc: pgsql-jdbc(at)postgresql(dot)org
Subject: Re: Connection exceptions
Date: 2009-06-20 03:39:15
Message-ID: 1245469155.1624.6.camel@ayaki (view raw, whole thread or download thread mbox)
Thread:
Lists: pgsql-jdbc
On Fri, 2009-06-19 at 12:37 +0200, Thomas Finneid wrote:

> Anybody got any best practices for how do I deal with connection problems
> in JDBC?

Most of your question really deals with the connection pooler you're
using, rather than JDBC its self. I'd start with the documentation for
DBCP.

That said, there are a few areas where you do need to handle connection
issues. The big one is that when you perform an operation, or a series
of operations wrapped into a transaction, they shouldn't change any
state in the wider program until they're complete, so you can retry them
if something goes wrong. You should be prepared to catch an SQLException
thrown at any point in the operation or series of operations. You
shouldn't care at what point in the process the exception was thrown.
When you catch it, you can test the SQLState to see if the error is
possibly transient and be prepared to retry the operation. (deadlocked
transaction? OK, retry. Connection broken? Obtain a new connection and
retry. etc) 

That way, you can just go ahead and use the connection you got from the
pooler. If it doesn't work for any reason, your code will deal with it.
After all, just because the connection was fine when the pooler tested
it doesn't mean it's still going to be fine by the time you start using
it; that's a race you'll win most of the time but are far from
guaranteed to win. Much better to make the code actually doing the work
handle failures cleanly rather than try to prevent them.

Think, for example, of a user with a laptop wandering around - they
might leave wifi range half way through an operation.

--
Craig Ringer


In response to

Responses

pgsql-jdbc by date

Next:From: Thomas FinneidDate: 2009-06-20 08:44:04
Subject: Re: Connection exceptions
Previous:From: Thomas FinneidDate: 2009-06-19 10:44:58
Subject: Re: Connection exceptions

Privacy Policy | About PostgreSQL
Copyright © 1996-2018 The PostgreSQL Global Development Group