JAvaデータ接続プールの使用.


1.package com.xiaobian;   
2.  
3./**  
4. *            
5. */  
6.import java.io.*;   
7.import java.sql.*;   
8.import java.util.*;   
9.import java.util.Date;   
10.  
11./**  
12. *    DBConnectionManager                         
13. *   .        getInstance()             
14. */  
15.public class DBConnectionManager {   
16.       
17.    public static void main(String[] args) {   
18.        DBConnectionManager connectionManager = DBConnectionManager.getInstance();   
19.           
20.        Connection conn =  connectionManager.getConnection("idb");   
21.            try {   
22.                Thread.sleep(10);   
23.            } catch (InterruptedException e) {   
24.                // TODO Auto-generated catch block   
25.                e.printStackTrace();   
26.            }   
27.        Connection conn1 =  connectionManager.getConnection("idb");   
28.        Connection conn2 =  connectionManager.getConnection("idb");   
29.        Connection conn3 =  connectionManager.getConnection("idb");   
30.        Connection conn4 =  connectionManager.getConnection("idb");   
31.        Connection conn5 =  connectionManager.getConnection("idb");   
32.        connectionManager.freeConnection("idb", conn);   
33.        connectionManager.freeConnection("idb", conn1);   
34.        connectionManager.freeConnection("idb", conn2);   
35.        connectionManager.freeConnection("idb", conn3);   
36.        connectionManager.freeConnection("idb", conn4);   
37.        connectionManager.freeConnection("idb", conn5);   
38.        Connection conn6 = connectionManager.getConnection("idb");   
39.        Connection conn7 = connectionManager.getConnection("idb");   
40.        System.out.println(" conn6 == "+conn6 +" conn7 == "+conn7);   
41.           
42.    }   
43.  
44.       
45.    static private DBConnectionManager instance; //        
46.  
47.    static private int clients; //   
48.  
49.    private Vector drivers = new Vector();   
50.  
51.    private PrintWriter log;   
52.  
53.    private Hashtable pools = new Hashtable();   
54.  
55.    /**  
56.     *       .           ,       
57.     *   
58.     * @return DBConnectionManager       
59.     */  
60.    static synchronized public DBConnectionManager getInstance() {   
61.        if (instance == null) {   
62.            instance = new DBConnectionManager();   
63.        }   
64.        clients++;   
65.        return instance;   
66.    }   
67.  
68.    /**  
69.     *                      
70.     */  
71.    private DBConnectionManager() {   
72.        init();   
73.    }   
74.  
75.    /**  
76.     *                    
77.     *   
78.     * @param name  
79.     *                            
80.     * @param con  
81.     *                  
82.     */  
83.    public void freeConnection(String name, Connection con) {   
84.        DBConnectionPool pool = (DBConnectionPool) pools.get(name);   
85.        if (pool != null) {   
86.            pool.freeConnection(con);   
87.        }   
88.    }   
89.  
90.    /**  
91.     *        (   )  .        ,                ,           
92.     *   
93.     * @param name  
94.     *                            
95.     * @return Connection      null  
96.     */  
97.    public Connection getConnection(String name) {   
98.        DBConnectionPool pool = (DBConnectionPool) pools.get(name);   
99.        //System.out.println(" pool == "+pool);   
100.        if (pool != null) {   
101.            return pool.getConnection();   
102.        }   
103.        return null;   
104.    }   
105.  
106.    /**  
107.     *         .       ,               ,          .  ,                 .  
108.     *   
109.     * @param name  
110.     *                   
111.     * @param time  
112.     *                       
113.     * @return Connection      null  
114.     */  
115.    public Connection getConnection(String name, long time) {   
116.        DBConnectionPool pool = (DBConnectionPool) pools.get(name);   
117.        if (pool != null) {   
118.            return pool.getConnection(time);   
119.        }   
120.        return null;   
121.    }   
122.  
123.    /**  
124.     *       ,           
125.     */  
126.    public synchronized void release() {   
127.        //                  
128.        if (--clients != 0) {   
129.            return;   
130.        }   
131.        Enumeration allPools = pools.elements();   
132.        while (allPools.hasMoreElements()) {   
133.            DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();   
134.            pool.release();   
135.        }   
136.        Enumeration allDrivers = drivers.elements();   
137.        while (allDrivers.hasMoreElements()) {   
138.            Driver driver = (Driver) allDrivers.nextElement();   
139.            try {   
140.                DriverManager.deregisterDriver(driver);   
141.                log("  JDBC     " + driver.getClass().getName() + "   ");   
142.            } catch (SQLException e) {   
143.                log(e, "      JDBC       : " + driver.getClass().getName());   
144.            }   
145.        }   
146.    }   
147.  
148.    /**  
149.     *              .  
150.     *   
151.     * @param props  
152.     *                   
153.     */  
154.    private void createPools(Properties props) {   
155.        Enumeration propNames = props.propertyNames();   
156.        while (propNames.hasMoreElements()) {   
157.            String name = (String) propNames.nextElement();   
158.            if (name.endsWith(".url")) {   
159.                String poolName = name.substring(0, name.lastIndexOf("."));   
160.                //System.out.println(" poolName ||"+poolName+"|");   
161.                String url = props.getProperty(poolName + ".url");   
162.                if (url == null) {   
163.                    log("      " + poolName + "  URL");   
164.                    continue;   
165.                }   
166.                String user = props.getProperty(poolName + ".user");   
167.                String password = props.getProperty(poolName + ".password");   
168.                String maxconn = props.getProperty(poolName + ".maxconn", "0");   
169.                int max;   
170.                try {   
171.                    max = Integer.valueOf(maxconn).intValue();   
172.                } catch (NumberFormatException e) {   
173.                    log("          : " + maxconn + " .   : " + poolName);   
174.                    max = 0;   
175.                }   
176.                DBConnectionPool pool = new DBConnectionPool(poolName, url,   
177.                        user, password, max);   
178.                pools.put(poolName, pool);   
179.                log("       " + poolName);   
180.            }   
181.        }   
182.    }   
183.  
184.    // --------------------------------------------------------------------------------   
185.  
186.    /**  
187.     *            
188.     */  
189.    private void init() {   
190.           
191.        InputStream fileinputstream = null;   
192.        try {   
193.            fileinputstream = new FileInputStream("./src/db.properties");   
194.        } catch (FileNotFoundException e1) {   
195.            e1.printStackTrace();   
196.        }   
197.        //BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(fileinputstream));   
198.  
199.        //InputStream is = getClass().getResourceAsStream("D:/workspace/UmessageSms/src/db.properties");   
200.        Properties dbProps = new Properties();   
201.        try {   
202.            dbProps.load(fileinputstream);   
203.        } catch (Exception e) {   
204.            e.printStackTrace();   
205.            System.err.println("        . "  
206.                    + "   db.properties CLASSPATH      ");   
207.            return;   
208.        }   
209.        String logFile = dbProps.getProperty("logfile",   
210.                "DBConnectionManager.log");   
211.           
212.        //System.out.println(dbProps.getProperty("logfile"));   
213.        try {   
214.            log = new PrintWriter(new FileWriter(logFile, true), true);   
215.        } catch (IOException e) {   
216.            System.err.println("        : " + logFile);   
217.            log = new PrintWriter(System.err);   
218.        }   
219.        loadDrivers(dbProps);   
220.        createPools(dbProps);   
221.    }   
222.  
223.    /**  
224.     *        JDBC      
225.     *   
226.     * @param props  
227.     *                
228.     */  
229.    private void loadDrivers(Properties props) {   
230.        String driverClasses = props.getProperty("drivers");   
231.        StringTokenizer st = new StringTokenizer(driverClasses);   
232.        while (st.hasMoreElements()) {   
233.            String driverClassName = st.nextToken().trim();   
234.            try {   
235.                Driver driver = (Driver) Class.forName(driverClassName)   
236.                        .newInstance();   
237.                DriverManager.registerDriver(driver);   
238.                drivers.addElement(driver);   
239.                log("    JDBC    " + driverClassName);   
240.            } catch (Exception e) {   
241.                log("    JDBC    : " + driverClassName + ",   : " + e);   
242.            }   
243.        }   
244.    }   
245.  
246.    /**  
247.     *              
248.     */  
249.    private void log(String msg) {   
250.        log.println(new Date() + ": " + msg);   
251.    }   
252.  
253.    /**  
254.     *                 
255.     */  
256.    private void log(Throwable e, String msg) {   
257.        log.println(new Date() + ": " + msg);   
258.        e.printStackTrace(log);   
259.    }   
260.  
261.    /** ************************************************************* */  
262.    /** ********************   DBConnectionPool******************** */  
263.    /** ************************************************************* */  
264.    /**  
265.     *             .            ,             .            ,           .  
266.     */  
267.    class DBConnectionPool {   
268.        private int checkedOut; //         
269.  
270.        private Vector freeConnections = new Vector(); //            
271.  
272.        private int maxConn; //                  
273.  
274.        private String name; //         
275.  
276.        private String password; //    null   
277.  
278.        private String URL; //     JDBC URL   
279.  
280.        private String user; //       null   
281.  
282.        /**  
283.         *          
284.         *   
285.         * @param name  
286.         *                   
287.         * @param URL  
288.         *                JDBC URL  
289.         * @param user  
290.         *                   null  
291.         * @param password  
292.         *                null  
293.         * @param maxConn  
294.         *                            
295.         */  
296.        public DBConnectionPool(String name, String URL, String user,   
297.                String password, int maxConn) {   
298.            this.name = name;   
299.            this.URL = URL;   
300.            this.user = user;   
301.            this.password = password;   
302.            this.maxConn = maxConn;   
303.        }   
304.  
305.        /**  
306.         *                 
307.         *   
308.         * @param con  
309.         *                       
310.         */  
311.        public synchronized void freeConnection(Connection con) {   
312.            //                
313.            freeConnections.addElement(con);   
314.            checkedOut--;   
315.            notifyAll(); //                
316.        }   
317.  
318.        /**  
319.         *             .                       
320.         *    ,      .               ,       ,                  .  
321.         */  
322.        public synchronized Connection getConnection() {   
323.            Connection con = null;   
324.            //System.out.println(" freeConnections.size() "+freeConnections.size());   
325.            if (freeConnections.size() > 0) {   
326.                //                
327.                con = (Connection) freeConnections.firstElement();   
328.                freeConnections.removeElementAt(0);   
329.                try {   
330.                    if (con.isClosed()) {   
331.                        log("    " + name + "        ");   
332.                        //       ,             
333.                        con = getConnection();   
334.                    }   
335.                } catch (SQLException e) {   
336.                    log("    " + name + "        ");   
337.                    //       ,             
338.                    con = getConnection();   
339.                }   
340.            } else if (maxConn == 0 || checkedOut < maxConn) {   
341.                con = newConnection();   
342.            }   
343.            if (con != null) {   
344.                checkedOut++;   
345.            }   
346.            System.out.println("con == "+con);   
347.            return con;   
348.        }   
349.  
350.        /**  
351.         *           .                       getConnection()  .  
352.         *   
353.         * @param timeout  
354.         *                         
355.         */  
356.        public synchronized Connection getConnection(long timeout) {   
357.            long startTime = new Date().getTime();   
358.            Connection con;   
359.            while ((con = getConnection()) == null) {   
360.                try {   
361.                    wait(timeout);   
362.                } catch (InterruptedException e) {   
363.                }   
364.                if ((new Date().getTime() - startTime) >= timeout) {   
365.                    // wait()           
366.                    return null;   
367.                }   
368.            }   
369.            return con;   
370.        }   
371.  
372.        /**  
373.         *         
374.         */  
375.        public synchronized void release() {   
376.            Enumeration allConnections = freeConnections.elements();   
377.            while (allConnections.hasMoreElements()) {   
378.                Connection con = (Connection) allConnections.nextElement();   
379.                try {   
380.                    con.close();   
381.                    log("     " + name + "      ");   
382.                } catch (SQLException e) {   
383.                    log(e, "       " + name + "    ");   
384.                }   
385.            }   
386.            freeConnections.removeAllElements();   
387.        }   
388.  
389.        /**  
390.         *         
391.         */  
392.        private Connection newConnection() {   
393.            Connection con = null;   
394.            try {   
395.                if (user == null) {   
396.                    con = DriverManager.getConnection(URL);   
397.                } else {   
398.                    con = DriverManager.getConnection(URL, user, password);   
399.                }   
400.                log("   " + name + "        ");   
401.            } catch (SQLException e) {   
402.                log(e, "      URL   : " + URL);   
403.                return null;   
404.            }   
405.            return con;   
406.        }   
407.    }   
408.} 

転載先:http://xiaobian.iteye.com/blog/111797