Advertisement
Guest User

Untitled

a guest
Apr 15th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. public class DatabaseConnection {
  2. private static final HashMap<Integer, ConWrapper> connections =
  3. new HashMap();
  4. private static String dbDriver, dbUrl, dbUser, dbPass;
  5. private static boolean propsInited = false;
  6. private static long connectionTimeOut = 30 * 60 * 60;
  7.  
  8. private DatabaseConnection() {}
  9.  
  10. public static Connection getConnection() {
  11. Thread cThread = Thread.currentThread();
  12. int threadID = (int) cThread.getId();
  13. ConWrapper ret = connections.get(threadID);
  14.  
  15. if (ret == null) {
  16. Connection retCon = connectToDB();
  17. ret = new ConWrapper(retCon);
  18. connections.put(threadID, ret);
  19. System.err.println("[Database] Thread [" + threadID + "] has created a new Database Connection.");
  20. }
  21.  
  22. return ret.getConnection();
  23. }
  24.  
  25. private static Connection connectToDB() {
  26. if (!propsInited) {
  27. PropertyReader dbReader;
  28.  
  29. try {
  30. dbReader = PropertyReader.load("db.cfg");
  31. } catch (IOException ex) {
  32. throw new DatabaseException(ex);
  33. }
  34.  
  35. dbDriver = dbReader.getProperty("driver");
  36. dbUrl = dbReader.getProperty("url");
  37. dbUser = dbReader.getProperty("user");
  38. dbPass = dbReader.getProperty("password");
  39. propsInited = true;
  40. }
  41.  
  42. try {
  43. Class.forName(dbDriver); // touch the MySQL driver
  44. } catch (ClassNotFoundException e) {
  45. throw new DatabaseException(e);
  46. }
  47.  
  48. try {
  49. Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
  50. return con;
  51. } catch (SQLException e) {
  52. throw new DatabaseException(e);
  53. }
  54. }
  55.  
  56. static class ConWrapper {
  57. private long lastAccessTime;
  58. private Connection connection;
  59.  
  60. public ConWrapper(Connection con) {
  61. this.connection = con;
  62. }
  63.  
  64. public Connection getConnection() {
  65. if (expiredConnection()) {
  66. try { // Assume that the connection is stale
  67. connection.close();
  68. } catch (SQLException err) {
  69. // Who cares
  70. }
  71. this.connection = connectToDB();
  72. }
  73.  
  74. lastAccessTime = System.currentTimeMillis(); // Record Access
  75. return this.connection;
  76. }
  77.  
  78. /**
  79. * Returns whether this connection has expired
  80. * @return
  81. */
  82. public boolean expiredConnection() {
  83. return System.currentTimeMillis() - lastAccessTime >= connectionTimeOut;
  84. }
  85. }
  86.  
  87. public static void closeAll() throws SQLException {
  88. for (ConWrapper con : connections.values()) {
  89. con.connection.close();
  90. }
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement