Witam.
Piszę obecnie aplikację wielowątkową, która operuje na bazie danych Postgre.
Utworzyłem w projekcie klasę - singleton, która ma odpowiadać za komunikację z BD.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Romek
*/
public class PostgreManager {
private PostgreManager() throws ClassNotFoundException, SQLException {
this(DEF_CONN, DEF_USER, DEF_PASS);
}
private PostgreManager(String conn, String usr, String pass) throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(conn, usr, pass);
counter = 0;
}
public static synchronized PostgreManager getInstance() throws ClassNotFoundException, SQLException {
if (instance == null) {
instance = new PostgreManager();
}
++counter;
return instance;
}
public String testConnection() throws SQLException{
return connection.getMetaData().getDatabaseProductVersion();
}
public ResultSet executeQuery(String query,int resultSetType,int resultSetConcurency) throws SQLException {
return connection.createStatement(resultSetType, resultSetConcurency).executeQuery(query);
}
public int executeUpdate(String query) throws SQLException{
return connection.createStatement().executeUpdate(query);
}
public synchronized void closeConnection() {
--counter;
if (counter == 0) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(PostgreManager.class.getName()).log(Level.SEVERE, null, ex);
}
instance = null;
}
}
private static PostgreManager instance;
private static final String DEF_CONN = "jdbc:postgresql://127.0.0.1:5432/pass";
private static final String DEF_USER = "postgres";
private static final String DEF_PASS = "root";
private static int counter;
private Connection connection;
}
Jak widać przy pierwszym użyciu zostaje załadowany sterownik jdbc i zainicjowane połączenie z bazą.
Z obiektu PostgreManager może jednocześnie korzystać wiele wątków. W momencie, gdy ostatni z nich
przestaje używać bazy (wywołuje closeConnection), połączenie powinno zostać zamknięte.
Czy należy wprowadzić dodatkową synchronizację w metodach executeQuery / executeUpdate ? ( na mój rozum taka synchronizacja odbywa się na poziomie bazy danych i nie jest tutaj potrzebna ).