Regarding connection pooling in java mail

Hi,
I’m implementing enterprise application which has ability of sending/receiving emails. I’m using java mail API 14.3. I have implemented the application level connection pooling which keep track of open folders, perform the time-out and other tasks. The connection pooling setting of IMAPStore is default setting. When we run our application in high load we get StoreClosedExcepton (Socket closed exception). My assumption is that when we perform some operation on folder, java mail also sends the noop command for store connection so there is no chance of store getting timeout.
Is there anything wrong in my understanding?

JavaMail does not do anything to keep the connection "alive". Servers are free to close
connections that have been unused for too long (usually 30 minutes). If you need to
keep the connection alive, you'll need to do some operation periodically, such as checking
the number of messages in the folder. Even that doesn't guard against server or network
failures, of course, so you always have to be prepared for a StoreClosedException or
FolderClosedException.

Similar Messages

  • How to make Connection Pooling in JAVA

    Dear Members
    I want to know that how can i make connection pooling in java and also how can i use that pool in my jsp/servlet application.
    Plz Describe in Detail.
    Thanks
    Vasim

    vasim_saiyad2000 wrote:
    Dear Members
    I want to know that how can i make connection pooling in java and also how can i use that pool in my jsp/servlet application.
    Plz Describe in Detail.
    Thanks
    VasimAs the previous poster is trying to suggest, the server you use will have datasource and connection pooling support. so look up in the manual how to set it up, or do a google search. For example if you use Tomcat, look here:
    http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

  • Connecting Pooling using Java Servlets

    Hello Friends I am in search of a programme to make a connection pooling using Java Servlets.
    Please let me know where i will get it or do post it.

    If you mean JDBC connection pools, one solution can be found here - http://www.javaexchange.com
    Chuck

  • Questions regarding Connection Pooling

    Hi
    i have some confusion regarding how connection pooling is implemented..i have been doing some digging in to this lately but the more i read the more confused i get. i have some doubts here, will any of the posters here kindly clear them
    a. Do i have to connect to my database via the DataSource method to take advantage of the connection pooling provided by my app server?..i have read conflicting information about this suggesting that Connection Pooling will not be provided to my app if i use DriverManager.getConnection()
    b. if i chose to use the DataSource method do i have to implement the ConnectionPoolDataSource interface to provide the connection pooling for my app?
    c. what is the best way to implement my own custom Connection pool?
    Thanx

    DriverManager.getConnection() literally creates, that is, builds a connection to the database using the values you previously supplied when you loaded the driver.
    A connection pool is an object that contains several already made connections to the database, and simply provides you with one of those existing connections. The confusion arises because a) the method name is frequently the same and b) the connection pool object calls the driver's getConnection() method to create several connections before lending any of them out.
    In other words:
    DriverManager.getConnection() builds a connection to the database.
    ConnectionPool.getConnection() fetches an existing connection.
    So, to answer your questions...
    A. This is correct. If you use DriverManager.getConnection(), you are indeed bypassing the Connection Pool entirely.
    B. I'm not familiar with DataSource specifically, but in general, a third party connection pool will either give you the interface (and you implement the details) or they will give you the class file containing the DataSource object. All you would have to do in the latter case is to import that file, then create a new instance of it using the new keyword ( DataSource foo = new DataSource(); ). I suspect DataSource is indeed the class file.
    C. Creating a connection pool is trivial and there are many examples of it - search on this forum or check out your favorite Java/JDBC programming book. Usually, the question "Should I use a connection pool and why?" is a more important question.

  • Urgent regarding connection pooling

    Please can someone thorw some light on how to implement connection pooling in simple way. I have seen lots of code snippet and did lots of reading.
    I need to know about how many classes i would need. and how do i use the classes.
    If someone can provide code snippet then that would be great
    thanks..please consider it to be urgent.

    Why reinvent the wheel?
    Most JDBC drivers will have connection pooling already implemented, and you just need to use it.
    You should be using the interface javax.sql.DataSource
    http://java.sun.com/j2se/1.5.0/docs/api/javax/sql/DataSource.html
    The recommended approach in Java/JSP is to have a DataSource object accessed via JNDI.
    Most servlet containers will let you define JNDI datasources to access the database connections from your app.
    For instance Tomcat: http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html
    Good luck,
    evnafets

  • How to compile connection pool sample java code

    I recently bought David Knox's "Effective Oracle Database 10g Security by Design", and have been working through his examples with client identifiers and how to leverage database security with anonymous connection pools.
    The database side of things I totally understand and have set up, but I now want to compile/run the java code examples, but don't know what is required to compile this.
    I'm running Oracle 10.2.0.4 (64-bit) Enterprise Edition on a Linux (RHEL 5) PC. Java version is 1.6.0_20. Relevant .bash_profile environment variables are as follows:
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
    export CLASSPATH=$ORACLE_HOME/jre:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
    export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
    When I try to compile, I get:
    oracle:DB10204$ java FastConnect.java
    Exception in thread "main" java.lang.NoClassDefFoundError: FastConnect/java
    Caused by: java.lang.ClassNotFoundException: FastConnect.java
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    Could not find the main class: FastConnect.java. Program will exit.
    The java source code of one of the examples is below. Is someone able to point me in the right direction as to how I get this to compile? Do I just have a syntax and/or environment configuration modification to do, or is there more to it than that to get this example working? Any help much appreciated.
    oracle:DB10204$   cat FastConnect.java
    package OSBD;
    import java.sql.*;
    import oracle.jdbc.pool.OracleDataSource;
    public class FastConnect
      public static void main(String[] args)
        long connectTime=0, connectionStart=0, connectionStop=0;
        long connectTime2=0, connectionStart2=0, connectionStop2=0;
        ConnMgr cm = new ConnMgr();
        // time first connection. This connection initializes pool.
        connectionStart = System.currentTimeMillis();
        Connection conn = cm.getConnection("SCOTT");
        connectionStop = System.currentTimeMillis();
        String query = "select ename, job, sal from person_view";
        try {
          // show security by querying from View
          Statement stmt = conn.createStatement();
          ResultSet rset = stmt.executeQuery(query);
          while (rset.next()) {
            System.out.println("Name:   " + rset.getString(1));
            System.out.println("Job:    " + rset.getString(2));
            System.out.println("Salary: " + rset.getString(3));
          stmt.close();
          rset.close();
          // close the connection which resets the database session
          cm.closeConnection(conn);
          // time subsequent connection as different user
          connectionStart2 = System.currentTimeMillis();
          conn = cm.getConnection("KING");
          connectionStop2 = System.currentTimeMillis();
          // ensure database can distinguish this new user
          stmt = conn.createStatement();
          rset = stmt.executeQuery(query);
          while (rset.next()) {
            System.out.println("Name:   " + rset.getString(1));
            System.out.println("Job:    " + rset.getString(2));
            System.out.println("Salary: " + rset.getString(3));
          stmt.close();
          rset.close();
          cm.closeConnection(conn);
        } catch (Exception e)    { System.out.println(e.toString()); }
        // print timing results
        connectTime = (connectionStop - connectionStart);
        System.out.println("Connection time for Pool: " + connectTime + " ms.");
        connectTime2 = (connectionStop2 - connectionStart2);
        System.out.println("Subsequent connection time: " +
                            connectTime2 + " ms.");
    }Code download is at: http://www.mhprofessional.com/getpage.php?c=oraclepress_downloads.php&cat=4222
    I'm looking at Chapter 6.

    stuartu wrote:
    When I try to compile, I get:
    oracle:DB10204$  java FastConnect.java
    Exception in thread "main" java.lang.NoClassDefFoundError: FastConnect/java
    Caused by: java.lang.ClassNotFoundException: FastConnect.java
    I will try to explain what is happening here.
    You are launching java telling it to run a class named 'java' in a package named 'FastConnect'
    and java says it cannot find that class.
    What you intended to do:
    $ # make the directory structure match the package structure
    $ mkdir OSBD
    $ # move the source file in the directory structure so it matches the package structure
    $ mv FastConnect.java OSBD/
    $ # compile OSBD/FastConnect.java to OSBD/FastConnect.class
    $ javac OSBD/FastConnect.java
    $ # launch java using the OSBD/FastConnect class
    $ java -cp . OSBD.FastConnectNote that the package 'OSBD' does not follow the recommended naming conventions
    you might consider changing that to 'osbd'.

  • Regarding Connection Pooling in Struts

    Hi All,
    I m using Struts for my web application. Now I want to use the Connection Pooling for my applicaiton.
    I m using JBoss, and Oracle 10gXE.
    My question are :
    1. Do I need to use Oracle Specific Connection Pooling or commons DBCP & Pool.
    2. Do I need to JNDI to bind my data source using mydatasource.xml in deploy folder of JBoss or
    define the datasource in struts-config.xml of my application.
    Which will be the efficient way?
    Presently I m defining my datasource in struts-config.xml. like :
    <data-sources>
           <data-source type="org.apache.commons.dbcp.BasicDataSource" key="msgds">
              <set-property property="description" value="OracleXE Data Source" />
              <set-property property="driverClassName" value="oracle.jdbc.OracleDriver" />
              <set-property property="url" value="jdbc:oracle:thin:@192.168.1.8:1521:XE" />
              <set-property property="minCount" value="2" />
              <set-property property="maxCount" value="50" />
              <set-property property="maxWait" value="5000" />
              <set-property property="username" value="ashish" />
              <set-property property="password" value="ashish" />
              <set-property property="autoCommit" value="true" />
              <set-property property="readOnly" value="false" />          
         </data-source>
    </data-sources>  
    3. How can i change it to an mydatasource.xml for JNDI. If is it like this,what is the error:
         <datasources>
           <local-tx-datasource>
             <jndi-name>msgds</jndi-name>
             <connection-url>jdbc:oracle:thin:@192.168.1.8:1521/XE</connection-url>
             <driver-class>oracle.jdbc.OracleDriver</driver-class>   
             <user-name>ashish</user-name>
              <password>ashish</password>
             <min-pool-size>5</min-pool-size>
             <max-pool-size>100</max-pool-size> 
           </local-tx-datasource>
         </datasources>Please if somebody have idea of it, plz help. If U have code for this plz send it to me.
    If u don't want to publish you can send it to my email id: [email protected].

    Just make sure all the JARS are in the classpath. BTW I use Iplanet but does that matter much ? Configure the Struts-config file for the datasource by adding the below tag text.
    <data-sources>
         <data-source type="org.apache.commons.dbcp.BasicDataSource" key="DBSTR">
              <set-property property="description" value="OracleXE Data Source" />
              <set-property property="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
              <set-property property="url" value="jdbc:oracle:thin:@155.136.118.169:1521:DBSID" />
              <set-property property="minCount" value="2" />
              <set-property property="maxCount" value="10" />
              <set-property property="maxWait" value="10000" />
              <set-property property="username" value="USER" />
              <set-property property="password" value="PASSWORD" />
              <set-property property="autoCommit" value="false" />
              <set-property property="readOnly" value="false" />          
         </data-source>
    and then access from your action or servlet by executing the below java code.
    dataSource = getDataSource(request,"DBSTR");
    conn = dataSource.getConnection();
    stmt = conn.createStatement();
    rs = stmt.executeQuery("select object_name from user_objects");
    while ( rs.next() ) {
    tmp = tmp + ": " + rs.getString("object_name");
    Piece of cake.

  • Connection Pooling in Java Application for interacting with Websphere MQ

    I have following infrastruture at my site.
    1> Machine #1 has below
    - Websphere MQSeries 6.0 (client setup - Slim Client)
    - OS = Windows 2003
    - i/p address : 10.1.11.10
    - Tomcat web server 5.5
    - No Websphere Application Server.
    2> Machine #2 has below
    - Websphere MQSeries 6.0 (Server setup)
    - OS = Windows 2003
    - i/p address : 10.1.11.21
    - Queue Manager Name : qMngr
    - Queue Name (client will put the message) : toServerQ
    - Queue Name (client will get the message) : fromServerQ
    - I have developed the web application in Tomcat web server 5.5 using MQ base classes for accessing the Websphere MQ.
    - Since it is web application there can be atleast 25 request at time.
    i.e. when client#1 request data from queue he must get data related to client#1 only not other than client#1.
    - For accessing the websphere MQ, I am using websphere MQ base classes in Client mode. (Not JMS)
    ==>>>> Source Code as follows
    Class MQInterface (Servlet) is used for getting the web request from user and reply the response in html format.
    public class MQInterface extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    String Output = "";
    System.out.println("!! Entered into Banking Servlet !!");
    String requestParam = request.getParameter("OPRN_CODE");
    if (requestParam.equalsIgnoreCase("GET_NAME_DETAIL")){
         String id = request.getParameter("id");
         Output = MQDataObject().getNameDetail(id);
    return Output;
    response.setContentType("text/html");
         PrintWriter out = response.getWriter();
    out.println(Output);
    Class MQDataObject is used for getting and putting data(message) into Websphere MQ.
    public class MQDataObject {
    private String hostname = "10.1.11.21";
    private String channel = "Chnl1";
    private String qManager = "qMngr1";
    private MQQueueManager qMgr;
    private ISISSSLAdaptor ssl;
    private ISISConfigHelper ConfigHelper;
    private String Output;
    public MQDataObject(){
    MQEnvironment.hostname = hostname;
    MQEnvironment.channel = channel;
    MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_MQSERIES_CLIENT);
    MQEnvironment.sslCipherSuite = "SSL_RER_WERH_3KIUD_EQW_CRT_SSA";
    try{
    ssl = new DEMOSSLAdaptor("DEMOSSLAdaptor.config");
    ConfigHelper = new ISISConfigHelper("MQConnection.config");
    }catch(Exception exception){
    System.out.println("Exception Details => " + exception);
    public String getNameDetail(String sendMessage){
    MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_MQSERIES_CLIENT);
         String msgText = "";
         try
    // Create a connection to the Queue Manager.
    qMgr = new MQQueueManager(qManager);
    // Set up the options on the queue we wish to open
    int openOutOptions = MQC.MQOO_OUTPUT;
    // Specify the queue to open and open option      
    MQQueue sendingQueue = qMgr.accessQueue("toServerQ",openOutOptions,null,null,null);
    // Define the MQ message and write some text in UTF format
    MQMessage sendingMessage = new MQMessage();
    sendingMessage.writeUTF(sendMessage);
    // Specify the message options..
    MQPutMessageOptions pmo = new MQPutMessageOptions();
    // Put message on the queue
    sendingQueue.put(sendingMessage,pmo);      
    // Close Sending Queue
    sendingQueue.close();          
    // Receiving the message back
    // Wait for 5 seconds to get reply from receiving queue
    Thread.sleep(5000);
    // Set up the options on receiving queue we wish to open
    int openInOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
    MQQueue receivingQueue = qMgr.accessQueue("fromServerQ",openInOptions,null,null,null);
    MQMessage receivingMessage = new MQMessage();
    // Set and Get the message options
    MQGetMessageOptions gmo = new MQGetMessageOptions();
    // Receiving the message off the queue.
    receivingQueue.get(receivingMessage,gmo);
    // Get the message from the receiving queue.
    msgText = receivingMessage.readStringOfByteLength(receivingMessage.getMessageLength());
    // Close Receiving Queue
    receivingQueue.close();
    // Close a connection to the Queue Manager.
    qMgr.disconnect();
    // Parse the received message using parser.
    String output = new IFXXMLParser().runExample(msgText);
    catch (MQException mqex){
    System.out.println("MQ Error : " + mqex);
    catch (Exception ex){
    System.out.println("General Error : " + ex);
    return Output;
    The message for sending the receiving is in XML format.
    Could any one help me following in questions.
    1> Since there is 30 request at time so for improve the performance and resources I need to do connection pooling.
    How can I achieve this using base classes.
    2> While retrieving (getting) the message for particular request how can I identify the response message.
    i.e. when client#1 request data from queue he must get data related to client#1 only not other than client#1.      
    because In above scenario there are separate queues for getting the message and putting the message.
    I have read the tutorial on connection pulling but I am little confused.
    i.e. default connection pool and MQSimpleConnectionManager.
    Thanking in Advance
    Sanjeev

    RahulSharna wrote:
    Well my advice would be something different here..
    Can you tell us whether the swing application that you are referring could be used by multiple client machines at the sametime ??
    If yes my advice for you would be a costly affair yet effective.
    Think of seperating your DAO layer from the swing client and you can make an attempt to make a centralized tier where DAO and business services are handled (also ensure that we you use connection pooling with a good tranaction support for building that tier).
    Think of publishing those as services either by using remoting tehnologies like RMI,Burlap, Hessian or as a Webservice.
    All you'd do is implementing respective client in the swing or client application which you are referring to..
    (if you things are too wierd and what is the best solution to go about the below url offers a good solution
    [http://tuscany.apache.org/]
    And in doing this you'd ensure there is not toomuch load on the Database and you'd have a centralized location where you can start tracing the problem.My guess would be that since the OP said that they have a server that they do in fact have a server.

  • Error Message while creating connection pool

    Hi all,
    I got the following error message while creating connection pool for the
    SQL Server thru the Application Server Admin Console.
    The message is,
    An error has occured.
    Operation 'create.Jdbc.ConnectionPool' failed in 'resources' Config Mbean. Target exception message :
    JdbcConnectionPool Already Exists: cannot add duplicate.
    But the connection pool for the SQL Server was not there in the list.
    What may be the possible reason for this error.
    i was trying to deploy a BMP entiy bean using the Sun Application Server.
    Prior deploying i just tried to create connection pool and test the connection using the Admin Console
    Please help me by providing a solution.

    Kriti Sundar Mazumder wrote:
    Hi
    I am getting an following error message, while creating database connection pool
    in weblogic 7.
    "<Jun 18, 2004 4:52:36 AM CDT> <Error> <JDBC> <001060> <Cannot startup connection
    pool "MyJDBCConnectionPool" java.sql.SQLException: [IBM][JDBC Driver] CLI0647E
    Error allocating DB2 environment handle, rc=-1.>"
    Can anyone help me out in this regard
    Regards
    KritiHi. I am no expert, but it sounds like a problem with the privileges the user
    has... The best thing is to step back to a simpler environment. Can you try
    connecting to DB2 with a simple program like utils.dbping? Please look at our
    driver docs for the DB2 driver, because there are several variations in connect
    properties depending on the type of DB2 you are connecting to...
    Joe

  • ADDRESS parse error in java mail

    Hi,
    I'm trying to retrieve the mails header and I get following error.
    javax.mail.MessagingException: Failed to load IMAP envelope: foldername=INBOX[uidvalidity:1222323518] : seqnum=1
    After digging source code of java mail I found that one of bad address is causing this problem. One of message is having following format of address.
    ("test" R "test" NIL "test1" "test.net.au").
    According to specifications (RFC 2060) address should have four component personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. When java mail tries parse this address it throws address parsing exception.
    Is anyone have come across this issue? I want to know is there any way to handle this scenario. Since other mail client seems to handle it e.g. thunderbird
    Regards
    Anupriya

    I'm using java mail 1.4.1. I downloaded the code from https://glassfish.dev.java.net/javaee5/mail//index.html and I haven't made any changes to code.
    I'm running msgshow.java program. I'm not running in any app server or web server.
    and following is output from program as i was mentioning earlier it's happening when I try to get the size of the message.
    DEBUG: setDebug: JavaMail version 1.4.1
    DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
    DEBUG: mail.imap.fetchsize: 16384
    * OK IMAP4 server (InterMail vM.7.05.02.03 201-2174-114-109-20070208) ready Tue, 25 Nov 2008 04:22:06 +0000 (GMT)
    A0 CAPABILITY
    * CAPABILITY IMAP4rev1 UIDPLUS NAMESPACE QUOTA
    A0 OK CAPABILITY completed
    DEBUG: protocolConnect login, host=test.com, [email protected], password=<non-null>
    A1 LOGIN [email protected] pass
    A1 OK LOGIN completed
    A2 CAPABILITY
    * CAPABILITY IMAP4rev1 UIDPLUS NAMESPACE QUOTA
    A2 OK CAPABILITY completed
    DEBUG: connection available -- size: 1
    A3 SELECT INBOX
    * 24 EXISTS
    * OK [UIDVALIDITY 1222323518] UIDs valid
    * OK [UIDNEXT 1031] Predicted next UID
    * FLAGS (\Answered \Flagged \Deleted \Draft \Seen)
    * OK [PERMANENTFLAGS (\* \Answered \Flagged \Deleted \Draft \Seen)] Permanent flags
    * 0 RECENT
    A3 OK [READ-WRITE] SELECT completed
    Getting message number: 20
    A4 FETCH 20 (BODY[])
    * 20 FETCH (BODY[] {569}
    Return-Path: <[email protected]>
    Received: from [127.0.0.1] by nssas01t.mx.test.com
    (InterMail vM.7.05.02.08 201-2174-114-118-20080528) with SMTP
    id <20071127054828.IKXY25226.nssas01t.mx.test.com@[127.0.0.1]>
    for <[email protected]>; Mon, 17 Nov 2008 05:48:28 +0000
    Date: Mon, 7 Feb 2008 21:52:25 -0800 (PST)
    From: "Test" R "Us"<[email protected]>
    Subject: afternoon meeting 1
    To: [email protected]
    Message-Id: <20071127054828.IKXY25226.nssas01t.mx.test.com@[127.0.0.1]>
    Hello
    A4 OK FETCH completed
    Return-Path: <[email protected]>
    Received: from [127.0.0.1] by nssas01t.mx.test.com
    (InterMail vM.7.05.02.08 201-2174-114-118-20080528) with SMTP
    id <20071127054828.IKXY25226.nssas01t.mx.test.com@[127.0.0.1]>
    for <[email protected]>; Mon, 17 Nov 2008 05:48:28 +0000
    Date: Mon, 7 Feb 2008 21:52:25 -0800 (PST)
    From: "Test" R "Us"<[email protected]>
    Subject: afternoon meeting 1
    To: [email protected]
    Message-Id: <20071127054828.IKXY25226.nssas01t.mx.test.com@[127.0.0.1]>
    Hello
    A5 FETCH 20 (FLAGS)
    * 20 FETCH (FLAGS (\Seen))
    A5 OK FETCH completed
    A6 FETCH 20 (ENVELOPE INTERNALDATE RFC822.SIZE)
    * 20 FETCH (ENVELOPE ("Mon, 7 Feb 2008 21:52:25 -0800 (PST)" "afternoon meeting 1" (("Test" R "Us" NIL "auto_786" "test.com")) (("Test" R "Us" NIL "auto_786" "test.com")) (("Test" R "Us" NIL "auto_786" "test.com")) ((NIL NIL "auto_786" "test.com")) NIL NIL NIL "<20071127054828.IKXY25226.nssas01t.mx.test.com@[127.0.0.1]>") INTERNALDATE "17-Nov-2008 05:48:46 +0000" RFC822.SIZE 569)
    A6 OK FETCH completed
    Oops, got exception! Failed to load IMAP envelope
    javax.mail.MessagingException: Failed to load IMAP envelope
         at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1226)
         at com.sun.mail.imap.IMAPMessage.getSize(IMAPMessage.java:387)
         at javax.mail.internet.MimeMessage.<init>(MimeMessage.java:229)
         at msgshow.main(msgshow.java:232)

  • How to make connection Pool for standalone Application

    hi
    I have got an application to craete a stadalone appliaction for connection pool.But it is taking m more time to create the Connection and fetch the data.
    import java.sql.*;
    import java.util.*;
    /** A class for preallocating, recycling, and managing
    *  JDBC connections.
    *  <P>
    *  Taken from Core Servlets and JavaServer Pages
    *  from Prentice Hall and Sun Microsystems Press,
    *  http://www.coreservlets.com/.
    *  &copy; 2000 Marty Hall; may be freely used or adapted.
    public class ConnectionPool implements Runnable {
      private String driver, url, username, password;
      private int maxConnections;
      private boolean waitIfBusy;
      private Vector availableConnections, busyConnections;
      private boolean connectionPending = false;
      public ConnectionPool(String driver, String url,
                            String username, String password,
                            int initialConnections,
                            int maxConnections,
                            boolean waitIfBusy)
          throws SQLException {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.maxConnections = maxConnections;
        this.waitIfBusy = waitIfBusy;
        if (initialConnections > maxConnections) {
          initialConnections = maxConnections;
        availableConnections = new Vector(initialConnections);
        busyConnections = new Vector();
        for(int i=0; i<initialConnections; i++) {
          availableConnections.addElement(makeNewConnection());
      public synchronized Connection getConnection()
          throws SQLException {
        if (!availableConnections.isEmpty()) {
          Connection existingConnection =
            (Connection)availableConnections.lastElement();
          int lastIndex = availableConnections.size() - 1;
          availableConnections.removeElementAt(lastIndex);
          // If connection on available list is closed (e.g.,
          // it timed out), then remove it from available list
          // and repeat the process of obtaining a connection.
          // Also wake up threads that were waiting for a
          // connection because maxConnection limit was reached.
          if (existingConnection.isClosed()) {
            notifyAll(); // Freed up a spot for anybody waiting
            return(getConnection());
          } else {
            busyConnections.addElement(existingConnection);
            return(existingConnection);
        } else {
          // Three possible cases:
          // 1) You haven't reached maxConnections limit. So
          //    establish one in the background if there isn't
          //    already one pending, then wait for
          //    the next available connection (whether or not
          //    it was the newly established one).
          // 2) You reached maxConnections limit and waitIfBusy
          //    flag is false. Throw SQLException in such a case.
          // 3) You reached maxConnections limit and waitIfBusy
          //    flag is true. Then do the same thing as in second
          //    part of step 1: wait for next available connection.
          if ((totalConnections() < maxConnections) &&
              !connectionPending) {
            makeBackgroundConnection();
          } else if (!waitIfBusy) {
            throw new SQLException("Connection limit reached");
          // Wait for either a new connection to be established
          // (if you called makeBackgroundConnection) or for
          // an existing connection to be freed up.
          try {
            wait();
          } catch(InterruptedException ie) {}
          // Someone freed up a connection, so try again.
          return(getConnection());
      // You can't just make a new connection in the foreground
      // when none are available, since this can take several
      // seconds with a slow network connection. Instead,
      // start a thread that establishes a new connection,
      // then wait. You get woken up either when the new connection
      // is established or if someone finishes with an existing
      // connection.
      public void makeBackgroundConnection() {
        connectionPending = true;
        try {
          Thread connectThread = new Thread(this);
          connectThread.start();
        } catch(OutOfMemoryError oome) {
          // Give up on new connection
      public void run() {
        try {
          Connection connection = makeNewConnection();
          synchronized(this) {
            availableConnections.addElement(connection);
            connectionPending = false;
            notifyAll();
        } catch(Exception e) { // SQLException or OutOfMemory
          // Give up on new connection and wait for existing one
          // to free up.
      // This explicitly makes a new connection. Called in
      // the foreground when initializing the ConnectionPool,
      // and called in the background when running.
      public Connection makeNewConnection()
          throws SQLException {
        try {
          // Load database driver if not already loaded
          Class.forName(driver);
          // Establish network connection to database
          Connection connection =
            DriverManager.getConnection(url, username, password);
          return(connection);
        } catch(ClassNotFoundException cnfe) {
          // Simplify try/catch blocks of people using this by
          // throwing only one exception type.
          throw new SQLException("Can't find class for driver: " +driver);
      public synchronized void free(Connection connection) {
        busyConnections.removeElement(connection);
        availableConnections.addElement(connection);
        // Wake up threads that are waiting for a connection
        notifyAll();
      public synchronized int totalConnections() {
        return(availableConnections.size() +
               busyConnections.size());
      /** Close all the connections. Use with caution:
       *  be sure no connections are in use before
       *  calling. Note that you are not <I>required</I> to
       *  call this when done with a ConnectionPool, since
       *  connections are guaranteed to be closed when
       *  garbage collected. But this method gives more control
       *  regarding when the connections are closed.
      public synchronized void closeAllConnections() {
        closeConnections(availableConnections);
        availableConnections = new Vector();
        closeConnections(busyConnections);
        busyConnections = new Vector();
      public void closeConnections(Vector connections) {
        try {
          for(int i=0; i<connections.size(); i++) {
            Connection connection =
              (Connection)connections.elementAt(i);
            if (!connection.isClosed()) {
              connection.close();
        } catch(SQLException sqle) {
          // Ignore errors; garbage collect anyhow
      public synchronized String toString() {
        String info =
          "ConnectionPool(" + url + "," + username + ")" +
          ", available=" + availableConnections.size() +
          ", busy=" + busyConnections.size() +
          ", max=" + maxConnections;
        return(info);
    }///// The Calling Class is below---------/////////////////
    import java.util.*;
    import java.sql.*;
    public class dbConnection
         public static void main(String[] args)
              String driver="oracle.jdbc.driver.OracleDriver";
              String username="ETS";
              String password="ETS";
              String url="jdbc:oracle:thin:@192.168.47.10:1521:ETS";
              int initialConnections=10;
            int maxConnections=50;
              boolean waitIfBusy=false;
              Connection con=null;
              Statement stmt = null;
              ResultSet rs = null;
              try
              System.out.println("Before constructory "+new java.util.Date());
              ConnectionPool pool=new ConnectionPool(driver,url,username,password,initialConnections,maxConnections,waitIfBusy);
              System.out.println("After constructory "+new java.util.Date());
                        con=pool.makeNewConnection();
         System.out.println("After Connection pool "+new java.util.Date());
                        String sql="select * from emp_master";
                        stmt = con.createStatement();
                        rs = stmt.executeQuery(sql);
                        while(rs.next()) {
                   int login1=rs.getInt("emp_code");     
                        System.out.println("Employee Code is  "+login1);
                        System.out.println("check 2");
                   String pass=rs.getString("PASSWORD");
                        System.out.println("Pass Word is "+pass);
              }catch(Exception e)
                   System.out.println("Exception is "+e);
              finally {
    }

    I once created a connection pool programatically with Apache DBCP API. It didnt took more than 10 lines. Unforchunetly I dont have to code with me now.
    But If I remember right there is a sample code for that in the Apache Commans DBCP documentation.

  • Unable to start the Universal Connection Pool error

    Hi,
    I am trying to deploy two instances of one and the same web application on Tomcat 6. I have application test.war, I have copied and renamed it to test2.war and moved both wars in Tomcat' webapps folder. One of those (which Tomcat decides to start first) correctly gets connection from PoolDataSourceFactory.getPoolDataSource() and works fine, but the second throws this exception while trying to get database connection.
    Please help,
    Thanks
    java.sql.SQLException: Unable to start the Universal Connection Pool: java.sql.SQLException: Unable to start the Universal Connection Pool: oracle.ucp.UniversalConnectionPoolException: MBean exception occurred while registering or unregistering the MBean
    at oracle.ucp.util.UCPErrorHandler.newSQLException(UCPErrorHandler.java:541)
    at oracle.ucp.jdbc.PoolDataSourceImpl.throwSQLException(PoolDataSourceImpl.java:587)
    at oracle.ucp.jdbc.PoolDataSourceImpl.startPool(PoolDataSourceImpl.java:276)
    at oracle.ucp.jdbc.PoolDataSourceImpl.getConnection(PoolDataSourceImpl.java:646)
    at oracle.ucp.jdbc.PoolDataSourceImpl.getConnection(PoolDataSourceImpl.java:613)
    at oracle.ucp.jdbc.PoolDataSourceImpl.getConnection(PoolDataSourceImpl.java:607)
    at com.avalonsql.core.db.connection.ConnectionWrapper.<init>(ConnectionWrapper.java:26)
    ... 31 more
    Caused by: java.sql.SQLException: Unable to start the Universal Connection Pool: oracle.ucp.UniversalConnectionPoolException: MBean exception occurred while registering or unregistering the MBean
    at oracle.ucp.util.UCPErrorHandler.newSQLException(UCPErrorHandler.java:541)
    at oracle.ucp.jdbc.PoolDataSourceImpl.throwSQLException(PoolDataSourceImpl.java:587)
    at oracle.ucp.jdbc.PoolDataSourceImpl.startPool(PoolDataSourceImpl.java:247)
    ... 35 more
    Caused by: oracle.ucp.UniversalConnectionPoolException: MBean exception occurred while registering or unregistering the MBean
    at oracle.ucp.util.UCPErrorHandler.newUniversalConnectionPoolException(UCPErrorHandler.java:421)
    at oracle.ucp.util.UCPErrorHandler.newUniversalConnectionPoolException(UCPErrorHandler.java:389)
    at oracle.ucp.admin.UniversalConnectionPoolManagerMBeanImpl.getUniversalConnectionPoolManagerMBean(UniversalConnectionPoolManagerMBeanImpl.java:149)
    at oracle.ucp.jdbc.PoolDataSourceImpl.startPool(PoolDataSourceImpl.java:242)
    ... 35 more
    Caused by: java.security.PrivilegedActionException: javax.management.InstanceAlreadyExistsException: oracle.ucp.admin:name=UniversalConnectionPoolManagerMBean
    at java.security.AccessController.doPrivileged(Native Method)
    at oracle.ucp.admin.UniversalConnectionPoolManagerMBeanImpl.getUniversalConnectionPoolManagerMBean(UniversalConnectionPoolManagerMBeanImpl.java:136)
    ... 36 more
    Caused by: javax.management.InstanceAlreadyExistsException: oracle.ucp.admin:name=UniversalConnectionPoolManagerMBean
    at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:453)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.internal_addObject(DefaultMBeanServerInterceptor.java:1484)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:963)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:917)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:312)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:482)
    at oracle.ucp.admin.UniversalConnectionPoolManagerMBeanImpl$2.run(UniversalConnectionPoolManagerMBeanImpl.java:142)
    ... 38 more

    I was getting the following exception.. However after setting the property ConnectionFactoryClassName, it went off..
    Caused by: java.sql.SQLException: Invalid Universal Connection Pool configuration: java.sql.SQLException: Unable to create factory class instance with provided factory class name: java.lang.ClassNotFoundException:
         at oracle.ucp.util.UCPErrorHandler.newSQLException(UCPErrorHandler.java:541)
         at oracle.ucp.jdbc.PoolDataSourceImpl.throwSQLException(PoolDataSourceImpl.java:587)
         at oracle.ucp.jdbc.PoolDataSourceImpl.createUniversalConnectionPool(PoolDataSourceImpl.java:523)
         at oracle.ucp.admin.UniversalConnectionPoolManagerBase.createConnectionPool(UniversalConnectionPoolManagerBase.java:554)
         ... 92 more
    Caused by: java.sql.SQLException: Unable to create factory class instance with provided factory class name: java.lang.ClassNotFoundException:
         at oracle.ucp.util.UCPErrorHandler.newSQLException(UCPErrorHandler.java:541)
         at oracle.ucp.jdbc.PoolDataSourceImpl.throwSQLException(PoolDataSourceImpl.java:587)
         at oracle.ucp.jdbc.PoolDataSourceImpl.initConnectionFactory(PoolDataSourceImpl.java:2457)
         at oracle.ucp.jdbc.PoolDataSourceImpl.createUniversalConnectionPool(PoolDataSourceImpl.java:386)
         ... 93 more
    Caused by: java.lang.ClassNotFoundException:
         at java.lang.Class.forNameImpl(Native Method)
         at java.lang.Class.forName(Class.java:169)
         at oracle.ucp.jdbc.PoolDataSourceImpl.initConnectionFactory(PoolDataSourceImpl.java:2444)
         ... 94 more
    Edited by: user7953709 on Aug 26, 2011 1:08 AM

  • NameNotFOundException in OC4J Connection Pool

    Hi,
    I am trying to implement connection pooling in OC4J.I modified the data-sources.xml file as follows:
    <!-- DataSource for Connection Pooling for MD Database -->
    <managed-data-source name="MDDS"
    connection-pool-name="SampleConnectionPool"
    jndi-name="jdbc/MDDS"/>
    <connection-pool name="SampleConnectionPool"
         min-connections="10"
         max-connections="100"
         inactivity-timeout="30">
    <connection-factory factory-class="oracle.jdbc.pool.OracleDataSource"
    user="xxx"
    password="xxx"
    url="jdbc:oracle:thin:@//localhost:1521/zzz">
    </connection-factory>
    </connection-pool>
    My Java Coding is as follows:
    javax.naming.InitialContext ic = new javax.naming.InitialContext();
         javax.sql.DataSource dataSource = (javax.sql.DataSource)ic.lookup("jdbc/MDDS");
         con = dataSource.getConnection();
    While executing the above code,I am getting "javax.naming.NameNotFoundException : jdbc/MDDS not found..
    Am I missing any step?.Thanks.

    Have you restarted the container?

  • OCI Connection Pool

    Hi,
    How do I use an OCI Connection Pool as a data source in OC4J?
    A sample data-sources.xml would be helpful.
    A snippet of servlet code would be great!
    Thanks

    Hi,
    OracleOCIConnectionPool extends OracleDataSource and I have
    created and attached a example test case OCIConnPoolJNDI.java of
    how to register this OCI pool object via JNDI InitialContext and
    look it up.
    The test assumes a default directory /tmp/JNDI/jndi_dir to exist
    that can be changed. You also need dbjava/lib/jndi.zip (or
    jndi.jar) and jis/lib/aurora_client.jar in your CLASSPATH
    * Different Config test for connection pooling
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    import java.math.BigDecimal;
    import oracle.jdbc.*;
    import oracle.jdbc.pool.*;
    import oracle.jdbc.oci.*;
    import oracle.sql.*;
    import javax.naming.*;
    import javax.naming.spi.*;
    import javax.sql.*;
    public class OCIConnPoolJNDI
    public static void main(String args[]) throws SQLException,
    NamingException
    String url = "jdbc:oracle:oci8:@" ;
    Context ctx = null;
    Hashtable env = new Hashtable (5);
    env.put (Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.fscontext.RefFSContextFactory");
    String fileDir = "file:/tmp/JNDI";
    System.out.println("fileDir = " + fileDir);
    env.put (Context.PROVIDER_URL, fileDir);
    ctx = new InitialContext(env);
    Properties poolconfig = new Properties( ) ;
    poolconfig.put(OracleOCIConnectionPool.CONNPOOL_MIN_LIMIT,
    "1") ;
    poolconfig.put(OracleOCIConnectionPool.CONNPOOL_MAX_LIMIT,
    "10") ;
    poolconfig.put(OracleOCIConnectionPool.CONNPOOL_INCREMENT,
    "2") ;
    poolconfig.put(OracleOCIConnectionPool.CONNPOOL_NOWAIT,
    "true") ;
    poolconfig.put(OracleOCIConnectionPool.TRANSACTIONS_DISTRIBUTED,
    "true") ;
    OracleOCIConnectionPool ods = new OracleOCIConnectionPool
    ("scott", "tiger", url, poolconfig);
    System.out.println("-- Doing the Bind --");
    ctx.bind ("jndi_dir/tkpjcpdb1",ods);
    ods.close();
    System.out.println("-- Doing the Lookup --");
    OracleOCIConnectionPool cpool = (OracleOCIConnectionPool)
    ctx.lookup
    ("jndi_dir/tkpjcpdb1");
    test1(cpool);
    // Close the connection
    cpool.close();
    cpool = null;
    public static void test1(OracleOCIConnectionPool cpool)
    throws SQLException
    System.out.println ("User = " + cpool.getUser());
    System.out.println ("URL = " + cpool.getURL());
    System.out.println ("Default Min poolsize Limit = " +
    cpool.getMinLimit());
    System.out.println ("Default Max poolsize Limit = " +
    cpool.getMaxLimit());
    System.out.println ("Default Connection Increment = " +
    cpool.getConnectionIncrement());
    java.util.Properties p = new java.util.Properties( );
    p.put (OracleOCIConnectionPool.CONNPOOL_MIN_LIMIT, "1") ;
    p.put (OracleOCIConnectionPool.CONNPOOL_MAX_LIMIT, "1") ;
    p.put (OracleOCIConnectionPool.CONNPOOL_INCREMENT, "0") ;
    cpool.setPoolConfig(p);
    System.out.println ("Set Min poolsize Limit = " +
    cpool.getMinLimit());
    System.out.println ("Set Max poolsize Limit = " +
    cpool.getMaxLimit());
    System.out.println ("Set Connection Increment = " +
    cpool.getConnectionIncrement());
    //get a connection from the pool
    OracleOCIConnection conn1 = (OracleOCIConnection)
    cpool.getConnection();
    OracleOCIConnection conn2 = (OracleOCIConnection)
    cpool.getConnection();
    OracleOCIConnection conn3 = (OracleOCIConnection)
    cpool.getConnection();
    System.out.println("ActiveSize of pool = " +
    cpool.getActiveSize());
    System.out.println("PoolSize = " + cpool.getPoolSize());
    testConn1(conn1);
    testConn1(conn2);
    testConn1(conn3);
    conn1.close();
    conn2.close();
    conn3.close();
    public static void testConn1 (OracleOCIConnection conn)
    throws SQLException
    System.out.println ("Got Pooled connection ...");
    // try operations via the pool
    Statement stmt = conn.createStatement ();
    ResultSet rset = stmt.executeQuery ("select USER from
    dual");
    while (rset.next ())
    System.out.println (" User = " + rset.getString (1));
    rset.close();
    stmt.close();

  • Help needed for Connection Pooling

    I want to know about connection pooling in java.Can anyone suggest a best tutorial or link to learn this.

    http://java.sun.com/developer/onlineTraining/Programming/JDCBook/conpool.html
    http://java.sun.com/products/jndi/tutorial/ldap/connect/pool.html
    or better Google it.

Maybe you are looking for

  • Formatting a seagate barracuda ata IV for mac?

    I have a couple of 20 GB seagate barracuda ata IV st320011a hard drives that I pulled out of an old sun server that was running sunOS 4.x solaris. Is there an easy way to erase and format them for Macs. I would like to use them as slaves on a couple

  • Min with group by

    i want to find the min(date) on a table using a select query that uses a group by, but i want to find the min(date) on the table and not the values grouped by. example col1 col2 1 10/04/07 2 11/04/07 1 09/04/07 4 04/04/06 want something like this sel

  • I just got a HP Deskjet 2540 and when I try to print (direct print) from my iPad I get the message that the printer is busy

    I just got a Hp Deskjet 2540 and when I try to  print (direct print) from my iPad, I get the message that the printer is busy.  Can anyone help?

  • I can't delete emails

    Hello, I have 37,000 emails that I would like to delete. They keep reappearing when I try to delete them. Rebuilding the inbox has not helped. Any thoughts? Thanks, Eli

  • Is Lightroom 5 talking/working with Photoshop CS-5?

    I just switch from Lightrooom 2 to Lightroom 5 and also to Photoshop CS-5 When ever I work on an image in Lightroom 5 and make changes and enhancements and when completed, I transfer the imges into Photoshop CS-5, my Lightroom 5 changes are NOT trans