L2DatabaseFactory.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (C) 2004-2015 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver;
  20. import java.sql.Connection;
  21. import java.sql.SQLException;
  22. import java.util.concurrent.Executors;
  23. import java.util.concurrent.ScheduledExecutorService;
  24. import java.util.concurrent.TimeUnit;
  25. import java.util.logging.Level;
  26. import java.util.logging.Logger;
  27. import com.l2jserver.gameserver.ThreadPoolManager;
  28. import com.mchange.v2.c3p0.ComboPooledDataSource;
  29. /**
  30. * This class manages the database connections.
  31. */
  32. public class L2DatabaseFactory
  33. {
  34. private static final Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());
  35. private static L2DatabaseFactory _instance;
  36. private static volatile ScheduledExecutorService _executor;
  37. private ComboPooledDataSource _source;
  38. /**
  39. * Instantiates a new l2 database factory.
  40. * @throws SQLException the SQL exception
  41. */
  42. public L2DatabaseFactory() throws SQLException
  43. {
  44. try
  45. {
  46. if (Config.DATABASE_MAX_CONNECTIONS < 2)
  47. {
  48. Config.DATABASE_MAX_CONNECTIONS = 2;
  49. _log.warning("A minimum of " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
  50. }
  51. _source = new ComboPooledDataSource();
  52. _source.setAutoCommitOnClose(true);
  53. _source.setInitialPoolSize(10);
  54. _source.setMinPoolSize(10);
  55. _source.setMaxPoolSize(Math.max(10, Config.DATABASE_MAX_CONNECTIONS));
  56. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  57. _source.setAcquireRetryDelay(500); // 500 milliseconds wait before try to acquire connection again
  58. _source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
  59. // if pool is exhausted
  60. _source.setAcquireIncrement(5); // if pool is exhausted, get 5 more connections at a time
  61. // cause there is a "long" delay on acquire connection
  62. // so taking more than one connection at once will make connection pooling
  63. // more effective.
  64. // this "connection_test_table" is automatically created if not already there
  65. _source.setAutomaticTestTable("connection_test_table");
  66. _source.setTestConnectionOnCheckin(false);
  67. // testing OnCheckin used with IdleConnectionTestPeriod is faster than testing on checkout
  68. _source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
  69. _source.setMaxIdleTime(Config.DATABASE_MAX_IDLE_TIME); // 0 = idle connections never expire
  70. // *THANKS* to connection testing configured above
  71. // but I prefer to disconnect all connections not used
  72. // for more than 1 hour
  73. // enables statement caching, there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
  74. _source.setMaxStatementsPerConnection(100);
  75. _source.setBreakAfterAcquireFailure(false); // never fail if any way possible
  76. // setting this to true will make
  77. // c3p0 "crash" and refuse to work
  78. // till restart thus making acquire
  79. // errors "FATAL" ... we don't want that
  80. // it should be possible to recover
  81. _source.setDriverClass(Config.DATABASE_DRIVER);
  82. _source.setJdbcUrl(Config.DATABASE_URL);
  83. _source.setUser(Config.DATABASE_LOGIN);
  84. _source.setPassword(Config.DATABASE_PASSWORD);
  85. /* Test the connection */
  86. _source.getConnection().close();
  87. if (Config.DEBUG)
  88. {
  89. _log.fine("Database Connection Working");
  90. }
  91. }
  92. catch (SQLException x)
  93. {
  94. if (Config.DEBUG)
  95. {
  96. _log.fine("Database Connection FAILED");
  97. }
  98. // re-throw the exception
  99. throw x;
  100. }
  101. catch (Exception e)
  102. {
  103. if (Config.DEBUG)
  104. {
  105. _log.fine("Database Connection FAILED");
  106. }
  107. throw new SQLException("Could not init DB connection:" + e.getMessage());
  108. }
  109. }
  110. /**
  111. * Shutdown.
  112. */
  113. public void shutdown()
  114. {
  115. try
  116. {
  117. _source.close();
  118. }
  119. catch (Exception e)
  120. {
  121. _log.log(Level.INFO, "", e);
  122. }
  123. try
  124. {
  125. _source = null;
  126. }
  127. catch (Exception e)
  128. {
  129. _log.log(Level.INFO, "", e);
  130. }
  131. }
  132. /**
  133. * Gets the single instance of L2DatabaseFactory.
  134. * @return single instance of L2DatabaseFactory
  135. * @throws SQLException the SQL exception
  136. */
  137. public static L2DatabaseFactory getInstance() throws SQLException
  138. {
  139. synchronized (L2DatabaseFactory.class)
  140. {
  141. if (_instance == null)
  142. {
  143. _instance = new L2DatabaseFactory();
  144. }
  145. }
  146. return _instance;
  147. }
  148. /**
  149. * Gets the connection.
  150. * @return the connection
  151. */
  152. public Connection getConnection()
  153. {
  154. Connection con = null;
  155. while (con == null)
  156. {
  157. try
  158. {
  159. con = _source.getConnection();
  160. if (Server.serverMode == Server.MODE_GAMESERVER)
  161. {
  162. ThreadPoolManager.getInstance().scheduleGeneral(new ConnectionCloser(con, new RuntimeException()), Config.CONNECTION_CLOSE_TIME);
  163. }
  164. else
  165. {
  166. getExecutor().schedule(new ConnectionCloser(con, new RuntimeException()), Config.CONNECTION_CLOSE_TIME, TimeUnit.MILLISECONDS);
  167. }
  168. }
  169. catch (SQLException e)
  170. {
  171. _log.log(Level.WARNING, "L2DatabaseFactory: getConnection() failed, trying again " + e.getMessage(), e);
  172. }
  173. }
  174. return con;
  175. }
  176. /**
  177. * The Class ConnectionCloser.
  178. */
  179. private static class ConnectionCloser implements Runnable
  180. {
  181. private static final Logger _log = Logger.getLogger(ConnectionCloser.class.getName());
  182. /** The connection. */
  183. private final Connection c;
  184. /** The exception. */
  185. private final RuntimeException exp;
  186. /**
  187. * Instantiates a new connection closer.
  188. * @param con the con
  189. * @param e the e
  190. */
  191. public ConnectionCloser(Connection con, RuntimeException e)
  192. {
  193. c = con;
  194. exp = e;
  195. }
  196. @Override
  197. public void run()
  198. {
  199. try
  200. {
  201. if (!c.isClosed())
  202. {
  203. _log.log(Level.WARNING, "Unclosed connection! Trace: " + exp.getStackTrace()[1], exp);
  204. }
  205. }
  206. catch (SQLException e)
  207. {
  208. _log.log(Level.WARNING, "", e);
  209. }
  210. }
  211. }
  212. /**
  213. * Gets the executor.
  214. * @return the executor
  215. */
  216. private static ScheduledExecutorService getExecutor()
  217. {
  218. if (_executor == null)
  219. {
  220. synchronized (L2DatabaseFactory.class)
  221. {
  222. if (_executor == null)
  223. {
  224. _executor = Executors.newSingleThreadScheduledExecutor();
  225. }
  226. }
  227. }
  228. return _executor;
  229. }
  230. /**
  231. * Gets the busy connection count.
  232. * @return the busy connection count
  233. * @throws SQLException the SQL exception
  234. */
  235. public int getBusyConnectionCount() throws SQLException
  236. {
  237. return _source.getNumBusyConnectionsDefaultUser();
  238. }
  239. /**
  240. * Gets the idle connection count.
  241. * @return the idle connection count
  242. * @throws SQLException the SQL exception
  243. */
  244. public int getIdleConnectionCount() throws SQLException
  245. {
  246. return _source.getNumIdleConnectionsDefaultUser();
  247. }
  248. }