一个连接池的例子(来自JIVE)(4)

发表于:2007-07-01来源:作者:点击数: 标签:
//文件:DbConnectionManager. java package com.qingtuo.db.pool; import java. sql .*; import java.io.*; import java.util.*; /** * Central manager of database connections. */ public class DbConnectionManager { private static DbConnectionProvid
//文件:DbConnectionManager.java

package com.qingtuo.db.pool;

import java.sql.*;
import java.io.*;
import java.util.*;

/**
* Central manager of database connections.
*/
public class DbConnectionManager {

    private static DbConnectionProvider connectionProvider;
    private static Object providerLock = new Object();

    /**
     * Returns a database connection from the currently active connection
     * provider.
     */
    public static Connection getConnection() {
        if (connectionProvider == null) {
            synchronized (providerLock) {
                if (connectionProvider == null) {
                    //Create the connection provider -- for now, this is hardcoded. For
                    //the next beta, I@#ll change this to load up the provider dynamically.
                    connectionProvider = new DbConnectionDefaultPool();
                    connectionProvider.start();
                }
            }
        }
        Connection con = connectionProvider.getConnection();
        if (con == null) {
            System.err.println("WARNING: DbConnectionManager.getConnection() failed to obtain a connection.");
        }
        return con;
    }

    /**
     * Returns the current connection provider. The only case in which this
     * method should be called is if more information about the current
     * connection provider is needed. Database connections should always be
     * obtained by calling the getConnection method of this class.
     */
    public static DbConnectionProvider getDbConnectionProvider() {
        return connectionProvider;
    }

    /**
     * Sets the connection provider. The old provider (if it exists) is shut
     * down before the new one is started. A connection provider <b>should
     * not</b> be started before being passed to the connection manager.
     */
    public static void setDbConnectionProvider(DbConnectionProvider provider) {
        synchronized (providerLock) {
            if (connectionProvider != null) {
                connectionProvider.destroy();
                connectionProvider = null;
            }
            connectionProvider = provider;
            provider.start();
        }
    }


}

原文转自:http://www.ltesting.net