I have built this database object below.
I want the methods update and query to be: 1. work in a multithread way (meaning 2 threads can access them at the same time - what synchronized prevents - that is why I cannot add it the the mehtod singutare). 2. if one thread had started open the database and the 2nd thread (that started after it) is trying to use that database - I don't want to get a situation where the 2nd thread is accessing the database when it is not yet open. in other words - I want it to be multithreaded in general but thread safe (atomic) when 1 thread is opening the data base for the first time.
Thanks, The class below is where I need to insert my logic (more specific - to the query and update methods).
public class SingeltonDB {
private static DBconnImpl db = null;
private static SingeltonDB singalDb = null;
private SingeltonDB(String username, String password) {
db = new DBconnImpl();
}
public static boolean isOpen() {
return (db != null);
}
public synchronized static SingeltonDB getInstance(String username,
String password) throws Exception {
if (db != null) {
throw (new Exception("The database is open"));
} else {
System.out.println("The database is now open");
singalDb = new SingeltonDB(username, password);
}
db.connect(username, password);
System.out.println("The database was connected");
return singalDb;
}
public synchronized static SingeltonDB getInstance() throws Exception {
if (db == null) {
throw (new Exception("The database is not open"));
}
return singalDb;
}
public void create(String tableName) throws Exception {
db.create(tableName);
}
public User query(String tableName, int rowID) throws Exception {
if (db == null) {
System.out.println("Error: the database is not open");
return null;
}
return (db.query(tableName, rowID));
}
public void update(String tableName, User user) throws Exception {
if (db == null) {
System.out.println("Error: the database is not open");
return;
}
db.update(tableName, user);
}
}