T
Tommy
Hi!
I have a singleton class that accesses a database (using jtds as
database driver).
class DatabaseAccessSingleton {
private static DatabaseAccessSingleton instance;
public static DatabaseAccessSingleton getInstance() {
if (instance==null) {
instance = new DatabaseAccessSingleton();
}
return instance;
}
public Vector getData() {
Vector data = new Vector();
try {
ResultSet rs =
connection.createStatement().executeQuery("SELECT * FROM TABLE");
while (rs.next()) {
data.add(rs.getString(1));
}
return data;
} catch (Exception e) {
}
}
}
That´s roughly the pattern that I use.
DatabaseAccessSingleton.getData() might be called by multiple threads.
So my question is, how to make it thread-safe?
In the jtds database driver I have read that while connection is
threadsafe, Statement is not.
So if I make the whole method synchronized, I guess that would solve
it. But then, only one thread at a time has access to the database, the
other threads would be blocked.
How can I allow multiple threads to use getData() without blocking? Or
is the method getData() even thread-safe as it is now?
Thanks!
Tommy
I have a singleton class that accesses a database (using jtds as
database driver).
class DatabaseAccessSingleton {
private static DatabaseAccessSingleton instance;
public static DatabaseAccessSingleton getInstance() {
if (instance==null) {
instance = new DatabaseAccessSingleton();
}
return instance;
}
public Vector getData() {
Vector data = new Vector();
try {
ResultSet rs =
connection.createStatement().executeQuery("SELECT * FROM TABLE");
while (rs.next()) {
data.add(rs.getString(1));
}
return data;
} catch (Exception e) {
}
}
}
That´s roughly the pattern that I use.
DatabaseAccessSingleton.getData() might be called by multiple threads.
So my question is, how to make it thread-safe?
In the jtds database driver I have read that while connection is
threadsafe, Statement is not.
So if I make the whole method synchronized, I guess that would solve
it. But then, only one thread at a time has access to the database, the
other threads would be blocked.
How can I allow multiple threads to use getData() without blocking? Or
is the method getData() even thread-safe as it is now?
Thanks!
Tommy