⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbpool.java

📁 一个数据库连接池
💻 JAVA
字号:
package dbpooltest.server;

import java.sql.DriverManager;
import java.sql.Connection;

public class DBPOOL {
    /**
     * 该类的维一实例
     */
    private static DBPOOL pool;
    /**
     * 容器的容量
     */
    private final int _size = 5;
    /**
     * con的容器
     */
    private Connection[] conns = new Connection[_size];

    private int _next=0;

    private int _oldest=0;

    /**
     * 私有构造函数,外部无法通过该构造函数创建对象.
     */
    private DBPOOL() {
        fillQueue();
    }

    static {
        pool = new DBPOOL();
    }

    public static DBPOOL getInstance() {
        return pool;
    }

    private void fillQueue() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException exp) {
            exp.printStackTrace();
        }
        for (int i = 0; i < _size; i++) {
            try {
                Connection con = DriverManager.getConnection(
                        "Jdbc:Odbc:DBPoolSource", "sa", "sa");
                put(con);
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        }
    }
    public synchronized void put(Connection con) {
        while (full()) {
            try {
                this.wait();
            } catch (InterruptedException ex) {
               // throw new ExceptionAdapter(ex);
            }
        }
        conns[_next] = con;
        System.out.println("反还资源成功!");
        _next = (_next + 1) % _size;
        this.notify();
    }

    public synchronized Connection getConnection() {
        while (empty()) {
            try {
                System.out.println("没有资源请等待!");
                this.wait();
            } catch (InterruptedException ex) {
                //throw new ExceptionAdapter(ex);
            }
        }
        Connection ret = conns[_oldest];
        conns[_oldest]=null;
        System.out.println("顺利得到资源!");
        _oldest = (_oldest + 1) % _size;
        notify();

        return ret;
    }

    public void returnConnection(Connection con){
        put(con);
    }

    private boolean empty() {
        return ((_next == _oldest)&&(conns[_oldest]==null));
    }

    private boolean full() {
        return ((_next == _oldest)&&(conns[_oldest]!=null));
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -