I would not expose the real connection from the
DbAccess
class.
The class has a reference to the broker, so it does not need to hold on to the thread. I don't know how you intend to use the class, but as it is you will hold the database connection even if it is not in use.
In the access class, implement access to the connection. If there is no connection, then each time a command is received a connection is taken from the broker. If a transaction is started, the connection is kept until it is committed or rolled back. A quick play example [not built]:
public class DbAccess {
private final static DbConnectionBroker broker;
private Connection connection;
private int commitCount;
public Static() {
DbAccess.broker = new DbConnectionBroker(...);
}
public DbAccess() {
this.commitCount = 0;
}
private Connection getConnection() {
if (this.connection == null) {
return DbAccess.getConnection();
}
return this.connection;
}
public void beginTransaction() {
this.commitCount++;
if (this.connection == null) {
this.connection = this.getConnection();
this.connection.beginTransaction();
}
}
public void commit() {
throws InvalidCommitState {
if (this.connection == null) {
throw new InvalidCommitState();
}
this.commitCount--;
if (this.commitCount == 0} {
this.connection.commit();
this.broker.releaseConnection(this.connection);
this.connection = null;
}
}
public void rollback() {
throws InvalidCommitState {
if (this.connection == null) {
throw new InvalidCommitState();
}
this.commitCount = 0;
this.connection.rollback();
this.broker.releaseConnection(this.connection);
this.connection = null;
}
public void execute (Statement statement) {
this.getConnection().execute(statement);
}
}