On Apr 15, 4:29 pm, "koenxj...@gmail.com" <koenxj...@gmail.com> wrote:
On Apr 15, 2:32 pm, Lew <l...@lewscanon.com> wrote:
koenxj...@gmail.com wrote:
package nl.nedcar.apollo.server.dao;
import java.sql.ResultSet;
public class FirstDAO extends AbstractDAO {
private static FirstDAO theInstance;
Here's your trouble. You will also note than none of the methods or other
accesses to shared state are synchronized. This code was designed to fail.
public static synchronized FirstDAO getInstance() {
if(theInstance == null) {
theInstance = new FirstDAO();
}
return theInstance;
}
public String getSomethingFromDatabase() throws Exception {
try {
ResultSet s = getStatement().executeQuery("select something from
users");
Note that
[a] ResultSet object is automatically closed when the Statement object that
generated it is closed, re-executed, or used to retrieve the next result from
a sequence of multiple results.
if(s.next()) {
return s.getString("username");
}
return null;
}
finally {
releaseConnection();
}
}
}
Yep. Designed to fail.
--
Lew
Thanks for your reply.
One more question to clarify things for me..
In my opinion, this legacy code is indeed designed to fail.
Because the superclass holds an instance of the connection.
But, what if, like I mentionned in my first post, an instance
of the datasource is kept in the superclass, not the connection
itself.
With the superclass code like:
protected Statement getStatement() throws SQLException {
return dataSource.getConnection().getStatement();
}
protected void releaseResources(ResultSet resultSet) throws
SQLException {
...
}
If 2 threads would access the getSomethingFromDatabase() method
simultaneously,
would..
a) both threads use a difference connection?
So operations on the resultset of one thread, would not interfere
with
the resultSet of the other thread.
b) one thread still take the resultSet of the other thread, breaking
the design?
This would meanSingletonDAO'sare always a no go.
Thanks!
Koen
I think it's thread safe and the answer is a).
Because only local variables are used.
And every caller gets their own copy of local variables in a method.