Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.yveltal.database;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.util.Hashtable;
- import java.util.Map;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- /**
- *
- * @author Sino
- *
- */
- public class DatabasePool {
- /**
- *
- */
- private final ExecutorService connectionPool = Executors.newCachedThreadPool();
- /**
- *
- */
- private final Map<String, Connection> connectionsCache = new Hashtable<String, Connection>();
- /**
- *
- */
- private Connection connection;
- /**
- *
- */
- public DatabasePool() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- *
- * @return
- */
- public void establishConnection(final Database database) {
- try {
- //Throw a callback and use a Future to asynchronously establish the connection
- final Future<Connection> connectionFuture = connectionPool.submit(new Callable<Connection>() {
- @Override
- public Connection call() throws Exception {
- return DriverManager.getConnection("", database.getUsername(), database.getPassword());
- }
- });
- //Stores this connection if successfully established into our connections cache
- connectionsCache.put(database.getDatabaseName(), connection = connectionFuture.get());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- *
- * @param runnable
- * @return
- */
- public Future<?> submit(Runnable task) {
- if (connectionsCache.isEmpty()) {
- throw new IllegalStateException("No connection ready for submission");
- }
- return connectionPool.submit(task);
- }
- /**
- *
- * @param statement
- * @return
- */
- public Future<?> prepare(final String databaseName, final DatabaseStatement statement) throws Exception {
- if (connectionsCache.containsKey(databaseName)) {
- final Future<?> prepare = connectionPool.submit(new Runnable() {
- @Override
- public void run() {
- statement.execute(connectionsCache.get(databaseName));
- }
- });
- return prepare;
- }
- return null;
- }
- /**
- *
- * @return
- */
- public Connection getConnection() {
- return connection;
- }
- /**
- *
- * @return
- */
- public Connection getConnection(String databaseName) {
- return connectionsCache.get(databaseName);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement