java will this threading setup work or what can i be doing wrong
- by Erik
Im a bit unsure and have to get advice.
I have the:
public class MyApp extends JFrame{
And from there i do;
MyServer = new MyServer (this);
MyServer.execute();
MyServer is a:
public class MyServer extends SwingWorker<String, Object> {
MyServer is doing listen_socket.accept() in the doInBackground()
and on connection it create a new
class Connection implements Runnable {
I have the belove DbHelper that are a singleton.
It holds an Sqlite connected. Im initiating it in the above MyApp
and passing references all the way in to my runnable:
class Connection implements Runnable {
My question is what will happen if there are two simultaneous read or `write?
My thought here was the all methods in the singleton are synchronized and
would put all calls in the queue waiting to get a lock on the synchronized method.
Will this work or what can i change?
public final class DbHelper {
private boolean initalized = false;
private String HomePath = "";
private File DBFile;
private static final String SYSTEM_TABLE = "systemtable";
Connection con = null;
private Statement stmt;
private static final ContentProviderHelper instance = new ContentProviderHelper ();
public static ContentProviderHelper getInstance() {
return instance;
}
private DbHelper () {
if (!initalized)
{
initDB();
initalized = true;
}
}
private void initDB()
{
DBFile = locateDBFile();
try {
Class.forName("org.sqlite.JDBC");
// create a database connection
con = DriverManager.getConnection("jdbc:sqlite:J:/workspace/workComputer/user_ptpp");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private File locateDBFile()
{
File f = null;
try{
HomePath = System.getProperty("user.dir");
System.out.println("HomePath: " + HomePath);
f = new File(HomePath + "/user_ptpp");
if (f.canRead())
return f;
else
{
boolean success = f.createNewFile();
if (success) {
System.out.println("File did not exist and was created " + HomePath);
// File did not exist and was created
} else {
System.out.println("File already exists " + HomePath);
// File already exists
}
}
} catch (IOException e) {
System.out.println("Maybe try a new directory. " + HomePath);
//Maybe try a new directory.
}
return f;
}
public String getHomePath()
{
return HomePath;
}
private synchronized String getDate(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public synchronized String getSelectedSystemTableColumn( String column) {
String query = "select "+ column + " from " + SYSTEM_TABLE ;
try {
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String value = rs.getString(column);
if(value == null || value == "")
return "";
else
return value;
}
} catch (SQLException e ) {
e.printStackTrace();
return "";
} finally {
}
return "";
}
}