So I'm making a server application in java, and I want the database requests to be event driven, so that it's non-blocking.
The way I'm doing this is to create the MySQL connection in another thread, so far I've got this:
package makeza.server.persistence;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
import makeza.server.WorldServer;
public final class MySQLNonblock extends Thread {
public Connection connection = null;
private Logger log = WorldServer.log;
private String host, port, user, pass, database;
@Override
public void run(){
init();
}
public MySQLNonblock(String hst, String prt, String usr, String pas, String dbase){
this.setDaemon(true);
this.setName("DatabaseThread");
this.host = hst;
this.port = prt;
this.user = usr;
this.pass = pas;
this.database = dbase;
}
public void init(){
log.info("Connecting to database...");
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" +
database + "?" + "user=" + user + "&password=" + pass);
log.info("Connected to database");
} catch (SQLException e) {
log.severe("Couldn't connect to database at " + host + ":" + port);
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
System.exit(1);
//e.printStackTrace();
}
}
}
I start the thread in another class, and it connects to the mysql server, and then the thread exits.
How do I make the thread persist once then run method ends so that I can use the mysql connection?