Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DatabaseConnection {
- private static final HashMap<Integer, ConWrapper> connections =
- new HashMap();
- private static String dbDriver, dbUrl, dbUser, dbPass;
- private static boolean propsInited = false;
- private static long connectionTimeOut = 30 * 60 * 60;
- private DatabaseConnection() {}
- public static Connection getConnection() {
- Thread cThread = Thread.currentThread();
- int threadID = (int) cThread.getId();
- ConWrapper ret = connections.get(threadID);
- if (ret == null) {
- Connection retCon = connectToDB();
- ret = new ConWrapper(retCon);
- connections.put(threadID, ret);
- System.err.println("[Database] Thread [" + threadID + "] has created a new Database Connection.");
- }
- return ret.getConnection();
- }
- private static Connection connectToDB() {
- if (!propsInited) {
- PropertyReader dbReader;
- try {
- dbReader = PropertyReader.load("db.cfg");
- } catch (IOException ex) {
- throw new DatabaseException(ex);
- }
- dbDriver = dbReader.getProperty("driver");
- dbUrl = dbReader.getProperty("url");
- dbUser = dbReader.getProperty("user");
- dbPass = dbReader.getProperty("password");
- propsInited = true;
- }
- try {
- Class.forName(dbDriver); // touch the MySQL driver
- } catch (ClassNotFoundException e) {
- throw new DatabaseException(e);
- }
- try {
- Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
- return con;
- } catch (SQLException e) {
- throw new DatabaseException(e);
- }
- }
- static class ConWrapper {
- private long lastAccessTime;
- private Connection connection;
- public ConWrapper(Connection con) {
- this.connection = con;
- }
- public Connection getConnection() {
- if (expiredConnection()) {
- try { // Assume that the connection is stale
- connection.close();
- } catch (SQLException err) {
- // Who cares
- }
- this.connection = connectToDB();
- }
- lastAccessTime = System.currentTimeMillis(); // Record Access
- return this.connection;
- }
- /**
- * Returns whether this connection has expired
- * @return
- */
- public boolean expiredConnection() {
- return System.currentTimeMillis() - lastAccessTime >= connectionTimeOut;
- }
- }
- public static void closeAll() throws SQLException {
- for (ConWrapper con : connections.values()) {
- con.connection.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement