|
|
My EJB has a method which will be running on a transaction started by a previous EJB.
This method has multiple calls to a makeValid method that needs to commit separately from the main transaction:
public class MyEJB{
private Connnection mainConnection = null;
private static final Connection staticConnection = (new ConnectionHelper()).getConnection();
public MyEJB(Connection conn){
this.mainConnection = conn;
}
public void myMethod(List myList){
//...
for (int j = 0; j < myList.size; j++) {
boolean valid = MyEJB.makeValid();
//...
}
}
private static synchronized boolean makeValid(){
staticConnection.setAutoCommit(false);
//...
staticConnection.commit();
return true;
}
}I will have multiple threads acceding myMethod and I need them to see each other changes to the database occurring in the makeValid method, so I have declared makeValid method as static synchronized.
My EJB uses the getConnection method from a helper class that goes like:
public class ConnectionHelper {
private Connection conn;
public Connection getConnection() throws Exception {
if(conn == null) {
conn = DataBaseConnectionResourceLocator.getConnection(Constants.DATABASE);
}
return conn;
}
//....
}I am not sure about the connection management that the application server will be doing, so I would appreciate comments on the following items:
1- When I use a static variable to hold reference to the 2nd connection, after I invoke "getConnection", this unique reference will be tied to a physical connection that the application server will get from the connection pool, so that the physical connection used in the application will also be unique
2- the first time I run the application, the getConnection method will return a new connection; but the next time I execute the application, as the static staticConnection still "lives", conn in the ConnectionHelper class will no longer be null, so that invoking getConnection will always be returning the same physical connection
3- If the physical connection is lost, I will have a valid reference tied to an invalid connection
4- As the connection is static, only when the application server is restarted I will be able to get a new valid connection
5- How could I guarantee that a valid physical connection is used each time the EJB is invoked?
6- When I create a 2nd connection object like this:
Connection specialPurposeConnection = (new ConnectionHelper()).getConnection();
the actual physical connection being used (got from the connection pool) may be the same that was returned for mainConnection, so when I will be invoking
specialPurposeConnection.commit();
I may unwantedly commit everything from both mainConnection and specialPurposeConnection.
I suppose some of these are wrong and it is simpler than I am making it...
Thank you in advance for help on this topic.