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
Views: Raw Message | Whole Thread | Download mbox | Resend email
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

Browse pgsql-jdbc by date

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