컴퓨터

확장된 ConnectionPool1클래스 예제

밤밤비나 2008. 1. 27. 20:44

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

public class ConnectionPool1 {
    private static ConnectionPool1 cp = null;
    private ConnectionFactory1 cf = null;
    private Vector pool = null;

    private int initCon = 0; 
    private int maxCon = 0;
    private int users = 0;

    private ConnectionPool1(int initCon, int maxCon) throws SQLException {
        this.initCon = initCon;
        this.maxCon = maxCon;
       
        cf = new ConnectionFactory1();
        pool = new Vector();

        for (int i=0; i < initCon; i++) {
            pool.add(createConnection());
        }
    }

    public static synchronized ConnectionPool1 getInstance() throws SQLException {
        if (cp == null) {
            cp = new ConnectionPool1(4,20);
        }

        return cp;
    }

    public synchronized Connection getConnection() throws SQLException {
        Connection conn = null;
       
        //커넥션을 얻어올 수 없다면 대기하고 있음
        while ((conn = getPooledConnection()) == null) {
            try {
                // releaseConnection메소드가 호출되면 통지 받는다.
                wait();
            } catch (InterruptedException ie) {}
        }

        // 사용 가능한 커넥션을 하나 얻었으면, users의 값을 하나 증가시켜줌
        users++;
        // 클라이인트 클래스에 커넥션을 넘겨줌
        return conn;
    }

    public synchronized void releaseConnection(Connection conn) {
        pool.add(conn);
        users--;
        notifyAll();
    }
   
    // 만들어진 커넥션이 최대 개수에 도달해서 더 이상 만들 수 없을 때는 null을 반환
    private Connection getPooledConnection() throws SQLException {
        Connection conn = null;
        int size = pool.size();

        if (size > 0) {
            conn = (Connection)(pool.elementAt(0));
            pool.removeElementAt(0);
        }  else if (users < maxCon || maxCon == 0) {
            pool.add(createConnection());
        }

        return conn;
    }

    private Connection createConnection() throws SQLException {
        Connection conn = cf.getConnection(ConnectionFactory1.ODBC);
        System.out.println("== a connection was created");

        return conn;
    }
}