I would like JdbcPersistenceManager to always have just one jdbcConnection and for it to be instantiated through: JdbcConnectionManager.getJdbcConnection()
Here's a simple pattern taken from (2004-11-01 | Head First Design Patterns | O'Reilly Media | 688p | by Elisabeth Freeman | ISBN-0596007124), possibly misused, misunderstood and out of place.
Should synchronized() lock on "this" or a specific, new (static?) field just dedicated to tracking locks? How would I do that?
public class JdbcPersistenceManager implements PersistenceManager {
private volatile Connection jdbcConnection;
/* ... */
private Connection getJdbcConnection() throws JdbcConnectionFailureException {
if (jdbcConnection == null) {
synchronized (this) {
if (jdbcConnection == null) {
jdbcConnection =
JdbcConnectionManager.getJdbcConnection(jdbcConnectionParameters);
}
}
}
// label:here
return jdbcConnection;
}
}
Assuming instantiation of jdbcConnection, even at the point marked as "label:here" if we want, just for argument's sake, how best to check that the connection is still valid and re-create it if it isn't?
ConnectionPooling is not what I'd like to do here. Just one connection... regenerating/reopening it if it's "null" or "invalid".
EDIT:
What I would like getJdbcConnection to do is:
1) dish out jdbcConnections, ensuring only one of them exists at any given time (no clients should be allowed to keep references to 2 different connections)
and
2) regenerate (i.e. re-invoke JdbcConnectionManager.getJdbcConnection()) the "private volatile Connection jdbcConnection" field if for some reason it got closed
(e.g. Client 1 comes along, gets a connection but closes it, client 2 comes along, the connection is not null but can't be used so she gets a regenerated one).
Note: I realise there's nothing stopping Client 1 from getting a connection whilst Client 2 gets the same one, as by design, and using it just one millisecond after Client 1 closes it through his reference... I don't know if that's solvable at all?