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

📄 streamconnectionpool.java

📁 有关j2me的很好的例子可以研究一下
💻 JAVA
字号:
/* * @(#)StreamConnectionPool.java	1.8 01/08/17 * Copyright (c) 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information").  You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * * Created on March 1, 2001, 4:34 PM * */package com.sun.midp.io.j2me.http;/** * A class representing a persistent connection pool that is used by the http * connection class to store persistent connections. Stream Connection  * Element elements are stored in the internal vector located in this class. * Each stream connection container element is marked when either in use or * not. As new connections are requested - the current connections in the pool * are searched for a match and inactivity. * * <p> There is a maximum number of simultanious connections that can be * in the pool at any one time. If for some reason there are no matching * connections available - a new one may be created (as long as it does not * exceed the maximum). If there number of connections in the pool exceeds  * the maximum - an adjustment is made to delete unused connections. Once * that happens (if at all) a new connection is created. If it can not create * a new connection an exception is raised. Once a connection is close down * a connection must be returned to the pool as inactive for another use. * * <p> Each individual stream connection stream element (or container)  * includes a in-use flag. Once a connection has been taken from the pool its * in-use flag is set to (true) and once that is closed its set to (false). * Once the connection stream element is (false) its available for reuse. * */import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.util.Vector;import java.util.Enumeration;import javax.microedition.io.StreamConnection;import javax.microedition.io.Connector;import javax.microedition.io.Connection;import com.sun.midp.io.InternalConnector;/** * This class implements the necessary functionality for the HTTP persistent * connection pool. This class contains individual http connection elements * (or containers) including whether or/not a that particular connection is * active. If a connection becomes inactive - its is available for reuse by * another http connection session or the same one. This reduces the connection * time for each supsequent connection. * * @author  Kerry Finn * @version 1.0 * */class StreamConnectionPool {    /** internal connection hash table */    private Vector              m_connections;    /** maximum connections */    private int               m_max_connections;    /** current connections in the pool */    private int               m_cur_connections;    /** connection active wait time */    private final long        CONNECTION_ACTIVE_WAIT_TIME = 60000;    /**     * Create a new instance of this class.     * We are initially unconnected this will create the     * first connection.     *     * @param number_of_connections The initial create number of connections      * @exception IOException       If some other kind of I/O error occurs.     */    public StreamConnectionPool(int number_of_connections)        throws IOException    {                this.m_max_connections = number_of_connections;                /*         * Allow only one connection in the pool - there may          * be point that one id required while the other one is cleaning         * up (m_max_connections+1).         */        m_connections = new Vector(m_max_connections+1);            }        /**     * Dumps the contents of the current pooled connections.     * TODO: will be taken out before last checkin.     */    public synchronized void dumpPool() {                if (m_connections.size() == 0)            return;        Enumeration cons = m_connections.elements();                System.out.println("============================================");        while (cons.hasMoreElements()) {            StreamConnectionElement scc =                 (StreamConnectionElement)cons.nextElement();            System.out.println("Host ["+scc.m_host+"]");            System.out.println("Port ["+scc.m_port+"]");            System.out.println("URL  ["+scc.m_url+"]");            System.out.println("Conn ["+scc.m_connection+"]");            System.out.println("InUse["+scc.m_in_use+"]");            System.out.println("-----------------------------------------");        }        System.out.println("============================================");                    }    /**     * Create a connection in the connection pool.     *     *      * @param p_url                 The URL for the connection     * @param p_host                The Hostname for the connection     * @param p_port                The port number for the connection     * @param p_connection          The name for the connection     * @exception IOException       If some other kind of I/O error occurs.     */    public synchronized void create(String p_url,                        String p_host,                        int p_port,                        String p_connection)         throws IOException    {        // System.err.println("TRACE: StreamConnectionPool::create()");                StreamConnectionElement scc =            createStreamConnectionElement(p_url,                                           p_host,                                           p_port,                                           p_connection);                scc.setInUse(false);        m_connections.addElement(scc);            }        /**     * Remove an instance of the stream connection container from     * the connection pool.     *     * @param scc                 The stream connection container to remove     * @return                    a boolean status of the remove object     */    public synchronized boolean remove(StreamConnectionElement scc) {                if (scc == null) {            return (true);        }        // System.err.println("TRACE: StreamConnectionPool::remove()");        // System.err.println("--------------------------------------------");        // System.err.println("Host ["+scc.m_host+"]");        // System.err.println("Port ["+scc.m_port+"]");        // System.err.println("URL  ["+scc.m_url+"]");        // System.err.println("Conn ["+scc.m_connection+"]");        // System.err.println("InUse["+scc.m_in_use+"]");        // System.err.println("--------------------------------------------");        // System.err.println("TRACE: ***** DUMP POOL *****"); this.dumpPool();        boolean rc = m_connections.removeElement(scc);        // System.err.println("TRACE: remove("+rc+") status returned.");        // System.err.println("TRACE: ***** DUMP POOL *****"); this.dumpPool();                       return (rc);    }        /**     * get an available connection and set the boolean flag to      * true (unavailable) in the connection pool. if one does not      * exist - create it and process accordingly.     *     * @param p_url                 The URL for the connection     * @param p_host                The Hostname for the connection     * @param p_port                The port number for the connection     * @param p_connection          The name for the connection     * @return                      A new stream connection container     * @exception IOException       If some other kind of I/O error occurs.     */    public synchronized StreamConnectionElement getConnection(String p_url,                                String p_host,                                int p_port,                                String p_connection)         throws IOException    {        StreamConnectionElement scc;        // System.err.println("TRACE: StreamConnectionPool::getConnection()");        if (m_connections.size() > 0) {            Enumeration cons = m_connections.elements();                        synchronized (m_connections) {                while (cons.hasMoreElements()) {                    scc = (StreamConnectionElement)cons.nextElement();                                        if ((p_host.equals(scc.m_host))                         && (p_port == scc.m_port)) {                                                if (scc.m_in_use == false) {                                                        // System.err.println("TRACE: found a connection");                            scc.setInUse(true);                            return (scc);                        }                                            } // end if equal(host, port)                                    } // end while loop                            } // end synchronized        } // end > 0 elements in the pool        // System.err.println("TRACE: no connection found need to create new");        scc =            createStreamConnectionElement(p_url,                                           p_host,                                           p_port,                                           p_connection);                // System.err.print  ("TRACE: StreamConnectionPool::");        // System.err.print  ("getConnection() -");        // System.err.print  ("host["+p_host+"] - port["+p_port+"] - url");        // System.err.println("["+p_url+"] create a new connection element!");        m_connections.addElement(scc);                      return (getConnection(p_url, p_host, p_port, p_connection));    }    /**     * create a new instance of the stream connection container     * that will be stored in the connection pool.     *     * @param p_url                 The URL for the connection     * @param p_host                The Hostname for the connection     * @param p_port                The port number for the connection     * @param p_connection          The name for the connection     * @return                      A new stream connection container     * @exception IOException       If some other kind of I/O error occurs.     */    private synchronized StreamConnectionElement         createStreamConnectionElement(                                        String p_url,                                        String p_host,                                        int p_port,                                        String p_connection)        throws IOException    {        StreamConnectionElement scc;        StreamConnection sc;        DataOutputStream dos;        DataInputStream dis;         /*         * first check and see if the maximum number of connections         * has been reached - if so delete the first one in the list (FIFO)         */        int cur_connections = m_connections.size();        long c_time = System.currentTimeMillis();        // System.err.print("TRACE: StreamConnectionPool::");        // System.err.print("createStreamConnectionElement() - ");        // System.err.print(" connect url:["+p_connection+"] -");        // System.err.print(" cur_connections:["+cur_connections+"] -");        // System.err.println(" max_connections:["+m_max_connections+"]");                if (cur_connections > m_max_connections) {            /*             * get the first unused element in the list and delete it             */            Enumeration cons = m_connections.elements();            while (cons.hasMoreElements()) {                scc = (StreamConnectionElement)cons.nextElement();                if (scc.m_in_use == false) {                    boolean rc = m_connections.removeElement(scc);                    break;                }                /*                 * check and see if the connection is old and delete it                 */                if ((c_time - scc.m_time > CONNECTION_ACTIVE_WAIT_TIME)) {                    // System.err.print("TRACE: StreamConnectionPool::");                    // System.err.print("createStreamConnectionElement() - ");                    // System.err.print("connection timed out (60 seconds)");                    // System.err.println("- remove element and make room");                    boolean rc = m_connections.removeElement(scc);                }                             }                        // System.err.println("TRACE: dump the pool"); this.dumpPool();            throw new IOException("exceeded the configured maximum "+                                  "number of connections");        }                sc = (StreamConnection)            InternalConnector.openInternal(                                           "socket://" + p_connection,                                           Connector.READ_WRITE, false);        dos = sc.openDataOutputStream();        dis = sc.openDataInputStream();                  scc =  new StreamConnectionElement(p_url,                                             p_host,                                             p_port,                                             p_connection,                                             sc,                                             dos,                                             dis);                return (scc);    }    /**     * Return an instance of the stream connection container to the      * connection pool     *     * @param returned            The stream connection container to remove     */    public synchronized void returnConnection(StreamConnection returned)    {               // System.err.print("TRACE: StreamConnectionPool::");        // System.err.println("returnConnection()");        StreamConnectionElement   scc;        StreamConnection          conn;        // System.err.println("TRACE: returnConnection()"); this.dumpPool();        synchronized (m_connections) {            Enumeration cons = m_connections.elements();            while (cons.hasMoreElements()) {                scc = (StreamConnectionElement)cons.nextElement();                conn = (StreamConnection)scc;                if (conn == returned) {                    // System.err.println("TRACE: found match reset InUse()");                    scc.setInUse(false);                    break;                }            } // end while loop        }// end synchronized        // System.err.println("TRACE: returnConnection()"); this.dumpPool();    }}

⌨️ 快捷键说明

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