Reputation: 494
Yes, I know..I wouldn't do it the single-connection way unless I was obligated.
With that said, let's say I want to make a singleton class, say DBConnection, with an sql Connection variable, and let's say I want the class to load info from a file about the database ip, user etc inside its constructor.
How can I possibly set the Connection variable as final static, if I need to first parse data from the file before assigning value on it?
The code so far (ignore the missing synch on getConnection):
final public class DBConnection {
transient private static Connection con;
private DBConnection()
[parse file, make url]
con = DriverManager.getConnection(url);
[...]
}
public static Connection getConnection(){
if (con == null)
new DBConnection();
return con;
}
}
Please also do tell if there's something awkward on the class, singleton-wise. In a sense, maybe I shouldn't have it as final after all, in case the connection closes and i have to do a new getConnection, but that would probably be a bad singleton class wouldn't it?
EDIT decided to change my aproach and make it the enum way
public enum Connect {
INSTANCE;
private Connection con;
Connect (){
[parse file]
con = DriverManager.getConnection(url);
[...]
}
public Connection getCon(){
return con;
}
However, how do I make sure noone tries
Channel.INSTANCE.getCon
before the constructor is finished?
Upvotes: 1
Views: 374
Reputation: 691715
If Connect.INSTANCE.getCon()
is called, then the INSTANCE enum must be constructed, then its constructor must have been executed before. There's no way such code could be executed if the constructor hasn't been executed before.
Upvotes: 0