ConnectionPool.java 16.2 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2004 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.database;

import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.Log;
16 17
import org.jivesoftware.util.JiveGlobals;

Matt Tucker's avatar
Matt Tucker committed
18 19
import java.io.IOException;
import java.sql.*;
20
import java.util.*;
Matt Tucker's avatar
Matt Tucker committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

/**
 * Database connection pool.
 *
 * @author Jive Software
 */
public class ConnectionPool implements Runnable {

    private String driver;
    private String serverURL;
    private String username;
    private String password;
    private int minCon;
    private int maxCon;
    private int conTimeout;
    private boolean mysqlUseUnicode;

    private Thread houseKeeper;
    private boolean shutdownStarted = false;

    private int conCount = 0;
    private int waitingForCon = 0;
    private Connection[] cons;
    private ConnectionWrapper[] wrappers;
    private Object waitLock = new Object();
    private Object conCountLock = new Object();

    public ConnectionPool(String driver, String serverURL, String username,
                          String password, int minCon, int maxCon,
                          double conTimeout, boolean mysqlUseUnicode) throws IOException {
        this.driver = driver;
        this.serverURL = serverURL;
        this.username = username;
        this.password = password;
        this.minCon = minCon;
        this.maxCon = maxCon;
        // Setting the timeout to 3 hours
        this.conTimeout = (int)(conTimeout * 1000 * 60 * 60 * 3); // convert to milliseconds
        this.mysqlUseUnicode = mysqlUseUnicode;

        if (driver == null) {
            Log.error("JDBC driver value is null.");
        }
        try {
            ClassUtils.forName(driver);
            DriverManager.getDriver(serverURL);
        }
        catch (ClassNotFoundException e) {
            Log.error("Could not load JDBC driver class: " + driver);
        }
        catch (SQLException e) {
            Log.error("Error starting connection pool.", e);
        }

        // Setup pool, open minimum number of connections
        wrappers = new ConnectionWrapper[maxCon];
        cons = new Connection[maxCon];

        boolean success = false;
        int maxTry = 3;

        for (int i = 0; i < maxTry; i++) {
            try {
                for (int j = 0; j < minCon; j++) {
                    createCon(j);
                    conCount++;
                }

                success = true;
                break;
            }
            catch (SQLException e) {
                // close any open connections
                for (int j = 0; j < minCon; j++) {
                    if (cons[j] != null) {
                        try {
                            cons[j].close();
                            cons[j] = null;
                            wrappers[j] = null;
                            conCount--;
                        }
                        catch (SQLException e1) { /* ignore */
                        }
                    }
                }

                // let admin know that there was a problem
                Log.error("Failed to create new connections on startup. " +
                        "Attempt " + i + " of " + maxTry, e);

                try {
                    Thread.sleep(10000);
                }
                catch (InterruptedException e1) { /* ignore */
                }
            }
        }

        if (!success) {
            throw new IOException();
        }

        // Start the background housekeeping thread
        houseKeeper = new Thread(this);
        houseKeeper.setDaemon(true);
        houseKeeper.start();
    }

    public Connection getConnection() throws SQLException {
        // if we're shutting down, don't create any connections
        if (shutdownStarted) {
            return null;
        }

        // Check to see if there are any connections available. If not, then enter wait-based
        // retry loop
137
        ConnectionWrapper wrapper = getCon();
Matt Tucker's avatar
Matt Tucker committed
138

139 140 141 142
        if (wrapper != null) {
            synchronized (wrapper) {
                wrapper.checkedout = true;
                wrapper.lockTime = System.currentTimeMillis();
Matt Tucker's avatar
Matt Tucker committed
143
            }
144
            return wrapper.getConnection();
Matt Tucker's avatar
Matt Tucker committed
145 146 147 148 149 150
        }
        else {
            synchronized (waitLock) {
                try {
                    waitingForCon++;
                    while (true) {
151
                        wrapper = getCon();
Matt Tucker's avatar
Matt Tucker committed
152

153
                        if (wrapper != null) {
Matt Tucker's avatar
Matt Tucker committed
154
                            --waitingForCon;
155 156 157
                            synchronized (wrapper) {
                                wrapper.checkedout = true;
                                wrapper.lockTime = System.currentTimeMillis();
Matt Tucker's avatar
Matt Tucker committed
158
                            }
159
                            return wrapper.getConnection();
Matt Tucker's avatar
Matt Tucker committed
160 161 162 163 164 165 166 167
                        }
                        else {
                            waitLock.wait();
                        }
                    }
                }
                catch (InterruptedException ex) {
                    --waitingForCon;
168
                    waitLock.notifyAll();
Matt Tucker's avatar
Matt Tucker committed
169 170 171 172 173 174 175 176 177 178 179

                    throw new SQLException("Interrupted while waiting for connection to " +
                            "become available.");
                }
            }
        }
    }

    public void freeConnection() {
        synchronized (waitLock) {
            if (waitingForCon > 0) {
180
                waitLock.notifyAll();
Matt Tucker's avatar
Matt Tucker committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
            }
        }
    }

    public void destroy() throws SQLException {
        // set shutdown flag
        shutdownStarted = true;

        // shut down the background housekeeping thread
        houseKeeper.interrupt();

        // wait 1/2 second for housekeeper to die
        try {
            houseKeeper.join(500);
        }
        catch (InterruptedException e) { /* ignore */
        }

        // check to see if there's any currently open connections to close
Gaston Dombiak's avatar
Gaston Dombiak committed
200
        for (int i = 0; i < conCount; i++) {
Matt Tucker's avatar
Matt Tucker committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
            ConnectionWrapper wrapper = wrappers[i];

            // null means that the connection hasn't been initialized, which will only occur
            // if the current index is greater than the current connection count
            if (wrapper == null) {
                break;
            }

            // if it's currently checked out, wait 1/2 second then close it anyways
            if (wrapper.checkedout) {
                try {
                    Thread.sleep(500);
                }
                catch (InterruptedException e) {/* ignore */
                }

                if (wrapper.checkedout) {
                    Log.info("Forcefully closing connection " + i);
                }
            }

            cons[i].close();
            cons[i] = null;
            wrappers[i] = null;
        }
    }

    public int getSize() {
        return conCount;
    }

    /**
     * Housekeeping thread. This thread runs every 30 seconds and checks connections for the
     * following conditions:<BR>
     * <p/>
     * <ul>
     * <li>Connection has been open too long - it'll be closed and another connection created.
     * <li>Connection hasn't been used for 30 seconds and the number of open connections is
     * greater than the minimum number of connections. The connection will be closed. This
     * is done so that the pool can shrink back to the minimum number of connections if the
     * pool isn't being used extensively.
     * <li>Unable to create a statement with the connection - it'll be reset.
     * </ul>
     */
    public void run() {
        while (true) {
            // print warnings on connections
            for (int i = 0; i < maxCon; i++) {
                if (cons[i] == null) {
                    continue;
                }

                try {
                    SQLWarning warning = cons[i].getWarnings();
                    if (warning != null) {
                        Log.warn("Connection " + i + " had warnings: " + warning);
                        cons[i].clearWarnings();
                    }
                }
                catch (SQLException e) {
                    Log.warn("Unable to get warning for connection: ", e);
                }
            }

            int lastOpen = -1;

            // go over every connection, check it's health
            for (int i = maxCon - 1; i >= 0; i--) {
                if (wrappers[i] == null) {
                    continue;
                }

                try {
                    long time = System.currentTimeMillis();

                    synchronized (wrappers[i]) {
                        if (wrappers[i].checkedout) {
                            if (lastOpen < i) {
                                lastOpen = i;
                            }
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299


                            // if the jive property "database.defaultProvider.checkOpenConnections"
                            // is true check open connections to make sure they haven't been open
                            // for more than XX seconds (600 by default)
                            if ("true".equals(JiveGlobals.getXMLProperty("database.defaultProvider.checkOpenConnections"))
                                    && !wrappers[i].hasLoggedException)
                            {
                                int timeout = 600;
                                try { timeout = Integer.parseInt(JiveGlobals.getXMLProperty("database.defaultProvider.openConnectionTimeLimit")); }
                                catch (Exception e) { /* ignore */ }

                                if (time - wrappers[i].lockTime > timeout * 1000) {
                                    wrappers[i].hasLoggedException = true;
                                    Log.warn("Connection has been held open for too long: ",
                                            wrappers[i].exception);
                                }
                            }

Matt Tucker's avatar
Matt Tucker committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
                            continue;
                        }
                        wrappers[i].checkedout = true;
                    }

                    // test health of connection
                    Statement stmt = null;
                    try {
                        stmt = cons[i].createStatement();
                    }
                    finally {
                        if (stmt != null) {
                            stmt.close();
                        }
                    }

                    // Can never tell
                    if (cons[i].isClosed()) {
                        throw new SQLException();
                    }

                    // check the age of the connection
                    if (time - wrappers[i].createTime > conTimeout) {
                        throw new SQLException();
                    }

                    // check to see if it's the last connection and if it's been idle for
                    // more than 60 secounds
                    if ((time - wrappers[i].checkinTime > 60 * 1000) && i > minCon &&
                            lastOpen <= i) {
                        synchronized (conCountLock) {
                            cons[i].close();
                            wrappers[i] = null;
                            cons[i] = null;
                            conCount--;
                        }
                    }

                    // Flag the last open connection
                    lastOpen = i;

                    // Unlock the connection
                    if (wrappers[i] != null) {
                        wrappers[i].checkedout = false;
                    }

                }
                catch (SQLException e) {
                    try {
                        synchronized (conCountLock) {
                            cons[i].close();
                            wrappers[i] = createCon(i);

                            // unlock the connection
                            wrappers[i].checkedout = false;
                        }
                    }
                    catch (SQLException sqle) {
                        Log.warn("Failed to reopen connection", sqle);

                        synchronized (conCountLock) {
                            wrappers[i] = null;
                            cons[i] = null;
                            conCount--;
                        }
                    }
                }
            }

            try {
                Thread.sleep(30 * 1000);
            }
            catch (InterruptedException e) {
                return;
            }
        }
    }

    private synchronized ConnectionWrapper getCon() throws SQLException {
        // check to see if there's a connection already available
        for (int i = 0; i < conCount; i++) {
            ConnectionWrapper wrapper = wrappers[i];

            // null means that the connection hasn't been initialized, which will only occur
            // if the current index is greater than the current connection count
            if (wrapper == null) {
                break;
            }

            synchronized (wrapper) {
                if (!wrapper.checkedout) {
                    wrapper.setConnection(cons[i]);
                    wrapper.checkedout = true;
                    wrapper.lockTime = System.currentTimeMillis();
394 395 396 397
                    if ("true".equals(JiveGlobals.getXMLProperty("database.defaultProvider.checkOpenConnections"))) {
                        wrapper.exception = new Exception();
                        wrapper.hasLoggedException = false;
                    }
Matt Tucker's avatar
Matt Tucker committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

                    return wrapper;
                }
            }
        }

        // won't create more than maxConnections
        synchronized (conCountLock) {
            if (conCount >= maxCon) {
                return null;
            }

            ConnectionWrapper con = createCon(conCount);
            conCount++;
            return con;
        }
    }

    /**
     * Create a connection, wrap it and add it to the array of open wrappers
     */
    private ConnectionWrapper createCon(int index) throws SQLException {
        try {
            Connection con = null;
            ClassUtils.forName(driver);

            if (mysqlUseUnicode) {
                Properties props = new Properties();
Matt Tucker's avatar
Matt Tucker committed
426
                props.put("characterEncoding", "UTF-8");
Matt Tucker's avatar
Matt Tucker committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                props.put("useUnicode", "true");
                if (username != null) {
                    props.put("user", username);
                }
                if (password != null) {
                    props.put("password", password);
                }
                con = DriverManager.getConnection(serverURL, props);
            }
            else {
                con = DriverManager.getConnection(serverURL, username, password);
            }

            if (con == null) {
                throw new SQLException("Unable to retrieve connection from DriverManager");
            }


            try {
                con.setAutoCommit(true);
            }
            catch (SQLException e) {/* ignored */
            }


            // A few people have been having problems because the default transaction
            // isolation level on databases is too high. READ_COMMITTED is a good
            // value for everyone to use because it provides the minimum amount of
            // locking that Jive needs to work well.
            try {
                // Supports transactions?
                if (con.getMetaData().supportsTransactions()) {
                    con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                }
            }
            catch (SQLException e) {
                // Ignore errors. A few databases don't support setting the transaction
                // isolation level, but ignoring the error shouldn't cause problems.
            }

            // create the wrapper object and mark it as checked out
            ConnectionWrapper wrapper = new ConnectionWrapper(con, this);
469 470 471
            if ("true".equals(JiveGlobals.getXMLProperty("database.defaultProvider.checkOpenConnections"))) {
                wrapper.exception = new Exception();
            }
Matt Tucker's avatar
Matt Tucker committed
472 473 474 475 476 477 478 479 480 481 482 483 484

            synchronized (conCountLock) {
                cons[index] = con;
                wrappers[index] = wrapper;
            }

            return wrapper;
        }
        catch (ClassNotFoundException e) {
            Log.error(e);
            throw new SQLException(e.getMessage());
        }
    }
485
}