Proposal: Automatic Resource Management

Bob Lee crazybob at crazybob.org
Fri Mar 6 16:02:12 PST 2009


On Fri, Mar 6, 2009 at 3:19 PM, Neal Gafter <neal at gafter.com> wrote:

> If you've already decided which resource-like APIs "count", then you
> don't need to ask us.


Did I unfairly discount some APIs? If so, please speak up.


> Personally, I'd like java.util.locks.Lock to be
> easier to use, though I understand this proposal doesn't solve that.


While hugely beneficial for I/O operations, this language feature would be
overkill for locks--locks don't throw exceptions, don't need to be nested,
aren't interacted with in the statement block, etc. A synchronized (Lock)
syntax wouldn't have been bad if introduced in Java 5 though.


> We've already discussed sql transactions too.
>

I thought it was clear that this language construct works fine w/ SQL
transactions. I guess not. It is unfortunate that Connection.close() doesn't
specify commit/rollback behavior (when auto-commit is disabled). .Net's
SqlConnection does the right thing (Go, M$! :-)). Most people would expect
that if you close a connection without explicitly committing the tx, the tx
should roll back. Unfortunately, Oracle's impl does just the opposite; it
commits the tx! Most people don't use the raw JDBC API to manage their txs,
but if you do, you have a couple options. a) Maybe your connection pool does
the right thing already--that is roll back uncommitted txs when returning a
connection to the pool. If you're not sure whether or not your impl does the
right thing, play it safe and b) wrap the connection.

  try (Connection c = safe(...)) {
    ...
  }

I should reiterate, most people use more modern, higher-level APIs like
@Transactional or even javax.transaction, not Connection. If you use
Connection to manage a tx, you have to pass the same Connection all over the
place--not recommended.

Bob



More information about the coin-dev mailing list