Project

General

Profile

1 1087 tao
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class represent a DBConnection pool. Another user can use the
4
 *    object to initial a connection pool, get db connection or return it.
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Jing Tao
8
 *
9
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27
28
package edu.ucsb.nceas.metacat;
29
30
import java.io.*;
31
import java.util.Vector;
32 1089 tao
import java.lang.*;
33 1087 tao
import java.sql.*;
34
import java.util.Stack;
35
import java.util.Hashtable;
36
import java.util.Enumeration;
37
38 2663 sgarg
import org.apache.log4j.Logger;
39
40 4080 daigle
import edu.ucsb.nceas.metacat.service.PropertyService;
41
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42
43 1087 tao
/**
44
 * A class represent a DBConnection pool. Another user can use the
45
 * object to initial a connection pool, get db connection or return it.
46
 * This a singleton class, this means only one instance of this class could
47
 * be in the program at one time.
48
 */
49 1092 tao
public class DBConnectionPool implements Runnable
50 1087 tao
{
51 1089 tao
52 1087 tao
  //static attributes
53
  private static DBConnectionPool instance;
54
  private static Vector connectionPool;
55 1092 tao
  private static Thread runner;
56 1849 tao
  private static int countOfReachMaximum = 0;
57 2663 sgarg
  private static Logger logMetacat = Logger.getLogger(DBConnectionPool.class);
58
59 4080 daigle
  private static int maxConnNum;
60
  private static int initConnNum;
61
  private static int incrConnNum;
62
  private static long maxAge;
63
  private static long maxConnTime;
64
  private static int maxUsageNum;
65
  private static String dbConnRecyclThrd;
66
  private static long cyclTimeDbConn;
67 1092 tao
68 4080 daigle
  final static int MAXIMUMCONNECTIONNUMBER;
69
  final static int INITIALCONNECTIONNUMBER;
70
  final static int INCREASECONNECTIONNUMBER;
71
  final static long MAXIMUMAGE;
72
  final static long MAXIMUMCONNECTIONTIME;
73
  final static int MAXIMUMUSAGENUMBER;
74
  final static String DBCONNECTIONRECYCLETHREAD ;
75
  final static long CYCLETIMEOFDBCONNECTION;
76
77
  static {
78
		int maxConnNum = 0;
79
		int initConnNum = 0;
80
		int incrConnNum = 0;
81
		long maxAge = 0;
82
		long maxConnTime = 0;
83
		int maxUsageNum = 0;
84
		String dbConnRecyclThrd = null;
85
		long cyclTimeDbConn = 0;
86
87
		try {
88
			// maximum connection number in the connection pool
89
			maxConnNum = Integer.parseInt(PropertyService
90
					.getProperty("database.maximumConnections"));
91
			initConnNum = Integer.parseInt(PropertyService
92
					.getProperty("database.initialConnections"));
93
			incrConnNum = Integer.parseInt(PropertyService
94
					.getProperty("database.incrementConnections"));
95
			maxAge = Integer.parseInt(PropertyService
96 4184 daigle
					.getProperty("database.maximumConnectionAge"));
97 4080 daigle
			maxConnTime = Long.parseLong(PropertyService
98
					.getProperty("database.maximumConnectionTime"));
99
			maxUsageNum = Integer.parseInt(PropertyService
100
					.getProperty("database.maximumUsageNumber"));
101
			dbConnRecyclThrd = PropertyService
102
					.getProperty("database.runDBConnectionRecycleThread");
103
			cyclTimeDbConn = Long.parseLong(PropertyService
104
					.getProperty("database.cycleTimeOfDBConnection"));
105
		} catch (PropertyNotFoundException pnfe) {
106
			System.err.println("Could not get property in static block: "
107
					+ pnfe.getMessage());
108
		}
109
110
		MAXIMUMCONNECTIONNUMBER = maxConnNum;
111
		INITIALCONNECTIONNUMBER = initConnNum;
112
		INCREASECONNECTIONNUMBER = incrConnNum;
113
		MAXIMUMAGE = maxAge;
114
		MAXIMUMCONNECTIONTIME = maxConnTime;
115
		MAXIMUMUSAGENUMBER = maxUsageNum;
116
		DBCONNECTIONRECYCLETHREAD  = dbConnRecyclThrd;
117
		CYCLETIMEOFDBCONNECTION = cyclTimeDbConn;
118
	}
119
120
  // the number for trying to check out a connection in the pool in
121
  // getDBConnection method
122 1217 tao
  final static int LIMIT = 2;
123 1089 tao
124
  final static int FREE = 0; //status of a connection
125
  final static int BUSY = 1; //statis of a connection
126 1087 tao
  /**
127
   * Returns the single instance, creating one if it's the
128
   * first time this method is called.
129
   */
130 1092 tao
  public static synchronized DBConnectionPool getInstance()
131 1089 tao
                                 throws SQLException
132 1087 tao
  {
133 2250 jones
    if (instance == null) {
134 1087 tao
      instance = new DBConnectionPool();
135 3078 jones
      Logger log = Logger.getLogger(DBConnectionPool.class);
136 4437 daigle
      log.debug("MaximumConnectionNumber: "+MAXIMUMCONNECTIONNUMBER);
137
      log.debug("Intial connection number: "+INITIALCONNECTIONNUMBER);
138
      log.debug("Increated connection Number: "+INCREASECONNECTIONNUMBER);
139
      log.debug("Maximum connection age: "+MAXIMUMAGE);
140
      log.debug("Maximum connection time: "+MAXIMUMCONNECTIONTIME);
141
      log.debug("Maximum usage count: "+MAXIMUMUSAGENUMBER);
142
      log.debug("Running recycle thread or not: "+DBCONNECTIONRECYCLETHREAD);
143
      log.debug("Cycle time of recycle: "+CYCLETIMEOFDBCONNECTION);
144 1087 tao
    }
145
    return instance;
146 3078 jones
  }
147 1089 tao
148 1092 tao
149 1089 tao
  /**
150 1087 tao
   * This is a private constructor since it is singleton
151
   */
152
153 1089 tao
  private DBConnectionPool()  throws SQLException
154 1087 tao
  {
155 1092 tao
    connectionPool = new Vector();
156 1089 tao
    initialDBConnectionPool();
157 1092 tao
    //running the thread to recycle DBConnection
158 1095 tao
    if (DBCONNECTIONRECYCLETHREAD.equals("on"))
159
    {
160
      runner = new Thread(this);
161
      runner.start();
162
    }
163 1087 tao
  }//DBConnection
164 1092 tao
165
  /**
166
   * Method to get the size of DBConnectionPool
167
   */
168
  public int getSizeOfDBConnectionPool()
169
  {
170
    return connectionPool.size();
171
  }
172 1087 tao
173 1092 tao
174 1087 tao
  /**
175
   * Method to initial a pool of DBConnection objects
176
   */
177 1092 tao
  private void initialDBConnectionPool() throws SQLException
178
  {
179 1087 tao
180
    DBConnection dbConn = null;
181
182 1089 tao
    for ( int i = 0; i < INITIALCONNECTIONNUMBER; i++ )
183 1087 tao
    {
184
      //create a new object of DBConnection
185 1089 tao
      //this DBConnection object has a new connection in it
186
      //it automatically generate the createtime and tag
187 1087 tao
      dbConn = new DBConnection();
188
      //put DBConnection into vetor
189
      connectionPool.add(dbConn);
190
    }
191
192
193 1092 tao
  }//initialDBConnectionPool
194
195
  /**
196
   * Method to get Connection object (Not DBConnection)
197
   */
198
  /*public static Connection getConnection() throws SQLException
199
  {
200
    DBConnection dbConn = null;
201
    //get a DBConnection
202
    dbConn = getDBConnection();
203
    //get connection object in DBConnection object
204
    //The following getConnections method is in DBConnection class
205
    return dbConn.getConnections();
206
  }*/
207
208 1089 tao
209 1095 tao
  /**
210
   * Method to get a DBConnection in connection pool
211
   * 1) try to get a DBConnection from DBConnection pool
212
   * 2) if 1) failed, then check the size of pool. If the size reach the
213
   *    maximum number of connection, throw a exception: couldn't get one
214
   * 3) If the size is less than the maximum number of connectio, create some
215
   *    new connections and recursive get one
216
   * @param methodName, the name of method which will check connection out
217
   */
218
  public static synchronized DBConnection getDBConnection(String methodName)
219
                                                throws SQLException
220
  {
221 2250 jones
    if (instance == null) {
222
      instance = DBConnectionPool.getInstance();
223
    }
224 1095 tao
    DBConnection db = null;
225 1217 tao
    int random = 0; //random number
226
    int index = 0; //index
227
    int size = 0; //size of connection pool
228 2663 sgarg
    logMetacat.debug("Try to checking out connection...");
229 1217 tao
    size = connectionPool.size();
230 2663 sgarg
    logMetacat.debug("size of connection pool: "+size);
231 1217 tao
232
     //try every DBConnection in the pool
233
    //every DBConnection will be try LIMITE times
234
    for (int j=0 ; j<LIMIT; j++)
235
    {
236
       //create a random number as the started index for connection pool
237
      //So that the connection ofindex of 0 wouldn't be a the heaviest user
238
      random = (new Double (Math.random()*100)).intValue();
239
      for (int i=0; i<size; i++)
240 1095 tao
      {
241 1217 tao
        index =(i+random)%size;
242
        db = (DBConnection) connectionPool.elementAt(index);
243 2663 sgarg
        logMetacat.debug("Index: "+index);
244
        logMetacat.debug("Tag: "+db.getTag());
245
        logMetacat.debug("Status: "+db.getStatus());
246 1095 tao
        //check if the connection is free
247
        if (db.getStatus()==FREE)
248
        {
249
          //If this connection is good, return this DBConnection
250
          if (validateDBConnection(db))
251
          {
252
253
            //set this DBConnection status
254
            db.setStatus(BUSY);
255 1122 tao
            //increase checkout serial number
256
            db.increaseCheckOutSerialNumber(1);
257 1095 tao
            //increase one usageCount
258
            db.increaseUsageCount(1);
259
            //set method name to DBConnection
260
            db.setCheckOutMethodName(methodName);
261 1299 tao
            db.setAutoCommit(true);
262 1095 tao
            //debug message
263 2663 sgarg
            logMetacat.debug("The connection is checked out: "
264
                                       +db.getTag());
265
            logMetacat.debug("The method for checking is: "
266
                                              +db.getCheckOutMethodName());
267
            logMetacat.debug("The age is "+db.getAge());
268
            logMetacat.debug("The usage is "+db.getUsageCount());
269
            logMetacat.debug("The conection time it has: "
270
                                                +db.getConnectionTime());
271 1095 tao
            //set check out time
272
            db.setCheckOutTime(System.currentTimeMillis());
273 1849 tao
            // set count of reach maximum 0 because it can check out
274
            countOfReachMaximum =0;
275 1095 tao
            return db;
276
          }//if
277
          else//The DBConnection has some problem
278
          {
279
            //close this DBConnection
280
            db.close();
281
            //remove it form connection pool
282 1217 tao
            connectionPool.remove(index);
283 1095 tao
            //insert a new DBConnection to same palace
284
            db = new DBConnection();
285 1217 tao
            connectionPool.insertElementAt(db, index);
286 1095 tao
          }//else
287
        }//if
288
      }//for
289 1217 tao
    }//for
290 1095 tao
291
    //if couldn't get a connection, we should increase DBConnection pool
292
    //if the connection pool size is less than maximum connection number
293 1217 tao
294
    if ( size < MAXIMUMCONNECTIONNUMBER )
295 1095 tao
    {
296 1217 tao
       if ((size+INCREASECONNECTIONNUMBER) < MAXIMUMCONNECTIONNUMBER)
297 1095 tao
       {
298
         //if we can create INCREASECONNECTIONNUMBER of new DBConnection
299
         //add to connection pool
300
         for ( int i=0; i<INCREASECONNECTIONNUMBER; i++)
301
         {
302
           DBConnection dbConn = new DBConnection();
303
           connectionPool.add(dbConn);
304
         }//for
305
       }//if
306
       else
307
       {
308
         //There is no enough room to increase INCREASECONNECTIONNUMBER
309
         //we create new DBCoonection to Maximum connection number
310 1217 tao
         for (int i= size+1; i<= MAXIMUMCONNECTIONNUMBER; i++)
311 1095 tao
         {
312
           DBConnection dbConn = new DBConnection();
313
           connectionPool.add(dbConn);
314
         }//for
315
       }//else
316
317
    }//if
318
    else
319
    {
320 1217 tao
      /*throw new SQLException("The maximum of " +MAXIMUMCONNECTIONNUMBER +
321 1095 tao
                            " open db connections is reached." +
322
                            " New db connection to MetaCat" +
323 1217 tao
                            " cannot be established.");*/
324 2663 sgarg
       logMetacat.fatal("The maximum of " +MAXIMUMCONNECTIONNUMBER +
325 1089 tao
                            " open db connections is reached." +
326
                            " New db connection to MetaCat" +
327 2663 sgarg
                            " cannot be established.");
328 1849 tao
       countOfReachMaximum ++;
329
       if (countOfReachMaximum >= 10)
330 1217 tao
       {
331 1849 tao
         countOfReachMaximum =0;
332 2663 sgarg
         logMetacat.fatal("finally could not get dbconnection");
333 1849 tao
         return null;
334 1217 tao
       }
335 1849 tao
       else
336 1217 tao
       {
337 1849 tao
         //if couldn't get a connection, sleep 20 seconds and try again.
338
         try
339
         {
340 2663 sgarg
           logMetacat.info("sleep for could not get dbconnection");
341 1849 tao
           Thread.sleep(5000);
342
         }
343
         catch (Exception e)
344
        {
345 2663 sgarg
           logMetacat.error("Exception in getDBConnection" + e.getMessage());
346 1849 tao
        }
347
      }
348 1217 tao
349 1095 tao
350 1089 tao
    }//else
351
352
    //recursive to get new connection
353 1217 tao
    return getDBConnection(methodName);
354 1089 tao
  }//getDBConnection
355 1217 tao
356
357 1087 tao
358
359 1089 tao
  /**
360
   * Method to check if a db connection works fine or not
361
   * Check points include:
362
   * 1. check the usageCount if it is too many
363
   * 2. check the dbconne age if it is too old
364
   * 3. check the connection time if it is too long
365
   * 4. run simple sql query
366
   *
367
   * @param dbConn, the DBConnection object need to check
368
   */
369
  private static boolean validateDBConnection (DBConnection dbConn)
370
  {
371
372 1217 tao
373 1089 tao
    //Check if the DBConnection usageCount if it is too many
374
    if (dbConn.getUsageCount() >= MAXIMUMUSAGENUMBER )
375
    {
376 2663 sgarg
      logMetacat.debug("Connection usageCount is too many: "+
377
      dbConn.getUsageCount());
378 1089 tao
      return false;
379
    }
380
381
    //Check if the DBConnection has too much connection time
382
    if (dbConn.getConnectionTime() >= MAXIMUMCONNECTIONTIME)
383
    {
384 2663 sgarg
      logMetacat.debug("Connection has too much connection time: "+
385
      dbConn.getConnectionTime());
386 1089 tao
      return false;
387
    }
388
389
    //Check if the DBConnection is too old
390
    if (dbConn.getAge() >=MAXIMUMAGE)
391
    {
392 2663 sgarg
      logMetacat.debug("Connection is too old: "+dbConn.getAge());
393 1089 tao
      return false;
394
    }
395
396
    //Try to run a simple query
397
    try
398
    {
399
      long startTime=System.currentTimeMillis();
400 1217 tao
      DatabaseMetaData metaData = dbConn.getMetaData();
401 1089 tao
      long stopTime=System.currentTimeMillis();
402
      //increase one usagecount
403
      dbConn.increaseUsageCount(1);
404
      //increase connection time
405
      dbConn.setConnectionTime(stopTime-startTime);
406 1087 tao
407 1089 tao
    }
408
    catch (Exception e)
409
    {
410 2663 sgarg
      logMetacat.error("Error in validateDBConnection: "
411
                                +e.getMessage());
412 1089 tao
      return false;
413
    }
414
415
    return true;
416
417
  }//validateDBConnection()
418
419 1092 tao
  /**
420
   * Method to return a connection to DBConnection pool.
421
   * @param conn, the Connection object need to check in
422
   */
423 1122 tao
  public static synchronized void returnDBConnection(DBConnection conn,
424
                                                              int serialNumber)
425 1092 tao
  {
426
    int index = -1;
427
    DBConnection dbConn = null;
428
429
    index = getIndexOfPoolForConnection(conn);
430
    if ( index ==-1 )
431
    {
432 2663 sgarg
      logMetacat.info("Couldn't find a DBConnection in the pool"
433 1092 tao
                                  +" which have same tag to the returned"
434 2663 sgarg
                                  +" DBConnetion object");
435 1092 tao
      return;
436
437
    }//if
438
    else
439
    {
440 1122 tao
      //check the paramter - serialNumber which will be keep in calling method
441
      //if it is as same as the object's checkoutserial number.
442
      //if it is same return it. If it is not same, maybe the connection already
443
      // was returned ealier.
444 2663 sgarg
      logMetacat.debug("serial number in Connection: "
445
                                      +conn.getCheckOutSerialNumber());
446
      logMetacat.debug("serial number in local: "+serialNumber);
447 1122 tao
      if (conn.getCheckOutSerialNumber() == serialNumber)
448
      {
449
        dbConn = (DBConnection) connectionPool.elementAt(index);
450
        //set status to free
451
        dbConn.setStatus(FREE);
452
        //count connection time
453
        dbConn.setConnectionTime
454 1092 tao
                          (System.currentTimeMillis()-dbConn.getCheckOutTime());
455 1095 tao
456 1122 tao
        //set check out time to 0
457
        dbConn.setCheckOutTime(0);
458 1217 tao
459 2663 sgarg
        logMetacat.debug("Connection: "+dbConn.getTag()+" checked in.");
460
        logMetacat.debug("Connection: "+dbConn.getTag()+"'s status: "
461
                                                    +dbConn.getStatus());
462 1217 tao
463 1122 tao
      }//if
464 1217 tao
      else
465
      {
466 2663 sgarg
        logMetacat.info("This DBConnection couldn't return");
467 1217 tao
      }//else
468 1092 tao
    }//else
469
470
471
  }//returnConnection
472
473
  /**
474
   * Given a returned DBConnection, try to find the index of DBConnection object
475
   * in dbConnection pool by comparing DBConnection' tag and conn.toString.
476
   * If couldn't find , -1 will be returned.
477
   * @param conn, the connection need to be found
478
   */
479
  private static synchronized int getIndexOfPoolForConnection(DBConnection conn)
480
  {
481
    int index = -1;
482
    String info = null;
483 1217 tao
    //if conn is null return -1 too
484
    if (conn==null)
485
    {
486
      return -1;
487
    }
488 1092 tao
    //get tag of this returned DBConnection
489
    info = conn.getTag();
490
    //if the tag is null or empty, -1 will be returned
491
    if (info==null || info.equals(""))
492
    {
493
      return index;
494
    }
495
    //compare this info to the tag of every DBConnection in the pool
496
    for ( int i=0; i< connectionPool.size(); i++)
497
    {
498
      DBConnection dbConn = (DBConnection) connectionPool.elementAt(i);
499
      if (info.equals(dbConn.getTag()))
500
      {
501
        index = i;
502
        break;
503
      }//if
504
    }//for
505
506
    return index;
507
  }//getIndexOfPoolForConnection
508
509
  /**
510
   * Method to shut down all connections
511
   */
512
  public static void release()
513
  {
514
515
    //shut down the backgroud recycle thread
516 1095 tao
    if (DBCONNECTIONRECYCLETHREAD.equals("on"))
517
    {
518
      runner.interrupt();
519
    }
520 1092 tao
    //cose every dbconnection in the pool
521
    synchronized(connectionPool)
522
    {
523
      for (int i=0;i<connectionPool.size();i++)
524
      {
525
        try
526
        {
527
          DBConnection dbConn= (DBConnection) connectionPool.elementAt(i);
528
          dbConn.close();
529
        }//try
530
        catch (SQLException e)
531
        {
532 2663 sgarg
          logMetacat.error("Error in release connection: "
533
                                            +e.getMessage());
534 1092 tao
        }//catch
535
      }//for
536
    }//synchronized
537
  }//release()
538
539
  /**
540
   * periodically to recycle the connection
541
   */
542
  public void run()
543
  {
544
    DBConnection dbConn = null;
545
    //keep the thread running
546
    while (true)
547
    {
548
      //check every dbconnection in the pool
549
      synchronized(connectionPool)
550
      {
551
        for (int i=0; i<connectionPool.size(); i++)
552
        {
553
          dbConn = (DBConnection) connectionPool.elementAt(i);
554 1095 tao
555 1122 tao
          //if a DBConnection conncectioning time for one check out is greater
556
          //than 30000 milliseconds print it out
557
          if (dbConn.getStatus()==BUSY &&
558
            (System.currentTimeMillis()-dbConn.getCheckOutTime())>=30000)
559 1095 tao
          {
560 2663 sgarg
            logMetacat.fatal("This DBConnection is checked out for: "
561 1122 tao
            +(System.currentTimeMillis()-dbConn.getCheckOutTime())/1000
562 2663 sgarg
            +" secs");
563
            logMetacat.fatal(dbConn.getTag());
564
            logMetacat.error("method: "
565
                                          +dbConn.getCheckOutMethodName());
566 1095 tao
567
          }
568
569
          //check the validation of free connection in the pool
570 1092 tao
          if (dbConn.getStatus() == FREE)
571
          {
572
            try
573
            {
574
              //try to print out the warning message for every connection
575 1122 tao
              if (dbConn.getWarningMessage()!=null)
576
              {
577 2663 sgarg
                logMetacat.warn("Warning for connection "
578
                  +dbConn.getTag()+" : "+ dbConn.getWarningMessage());
579 1122 tao
              }
580 1092 tao
              //check if it is valiate, if not create new one and replace old one
581
              if (!validateDBConnection(dbConn))
582
              {
583 2663 sgarg
                logMetacat.debug("Recyle it: "+ dbConn.getTag());
584 1092 tao
                //close this DBConnection
585
                dbConn.close();
586
                //remove it form connection pool
587
                connectionPool.remove(i);
588
                //insert a new DBConnection to same palace
589
                dbConn = new DBConnection();
590
                connectionPool.insertElementAt(dbConn, i);
591 1122 tao
               }//if
592 1092 tao
            }//try
593
            catch (SQLException e)
594
            {
595 2663 sgarg
              logMetacat.error("Error in DBConnectionPool.run: "
596
                                              +e.getMessage());
597 1092 tao
            }//catch
598
          }//if
599
        }//for
600
      }//synchronize
601 1095 tao
      //Thread sleep
602 1092 tao
      try
603
      {
604 1095 tao
        Thread.sleep(CYCLETIMEOFDBCONNECTION);
605 1092 tao
      }
606
      catch (Exception e)
607
      {
608 2663 sgarg
        logMetacat.error("Error in DBConnectionPool.run: "
609
                                              +e.getMessage());
610 1092 tao
      }
611
    }//while
612
  }//run
613
614 1217 tao
  /**
615
   * Method to get the number of free DBConnection in DBConnection pool
616
   */
617 1219 tao
  public static synchronized int getFreeDBConnectionNumber()
618 1217 tao
  {
619
    int numberOfFreeDBConnetion = 0; //return number
620
    DBConnection db = null; //single DBconnection
621
    int poolSize = 0; //size of connection pool
622
    //get the size of DBConnection pool
623
    poolSize = connectionPool.size();
624
    //Check every DBConnection in the pool
625
    for ( int i=0; i<poolSize; i++)
626
    {
627
628
      db = (DBConnection) connectionPool.elementAt(i);
629
      //check the status of db. If it is free, count it
630
      if (db.getStatus() == FREE)
631
      {
632
        numberOfFreeDBConnetion++;
633
      }//if
634
    }//for
635
    //return the count result
636
    return numberOfFreeDBConnetion;
637
  }//getFreeDBConnectionNumber
638
639
   /**
640
   * Method to print out the method name which have busy DBconnection
641
   */
642
  public void printMethodNameHavingBusyDBConnection()
643
  {
644
645
    DBConnection db = null; //single DBconnection
646
    int poolSize = 0; //size of connection pool
647
    //get the size of DBConnection pool
648
    poolSize = connectionPool.size();
649
    //Check every DBConnection in the pool
650
    for ( int i=0; i<poolSize; i++)
651
    {
652
653
      db = (DBConnection) connectionPool.elementAt(i);
654
      //check the status of db. If it is free, count it
655
      if (db.getStatus() == BUSY)
656
      {
657 2663 sgarg
        logMetacat.warn("This method having a busy DBConnection: "
658
                                    +db.getCheckOutMethodName());
659
        logMetacat.warn("The busy DBConnection tag is: "
660
                                    +db.getTag());
661 1217 tao
      }//if
662
    }//for
663
664
  }//printMethodNameHavingBusyDBConnection
665
666 1219 tao
  /**
667
   * Method to decrease dbconnection pool size when all dbconnections are idle
668
   * If all connections are free and connection pool size greater than
669
   * initial value, shrink connection pool size to intital value
670
   */
671 1220 tao
  public static synchronized boolean shrinkConnectionPoolSize()
672 1219 tao
  {
673
     int connectionPoolSize = 0; //store the number of dbconnection pool size
674
     int freeConnectionSize = 0; //store the number of free dbconnection in pool
675
     int difference = 0; // store the difference number between connection size
676
                         // and free connection
677 1220 tao
     boolean hasException = false; //to check if has a exception happend
678
     boolean result = false; //result
679
     DBConnection conn = null; // the dbconnection
680 1219 tao
     connectionPoolSize = connectionPool.size();
681
     freeConnectionSize = getFreeDBConnectionNumber();
682 2716 sgarg
     difference = connectionPoolSize - freeConnectionSize;
683
684 2714 sgarg
     if(freeConnectionSize < connectionPoolSize){
685 2716 sgarg
    	 logMetacat.warn(difference + " connection(s) " +
686
                        "being used and connection pool size is " +connectionPoolSize);
687 2714 sgarg
     } else {
688 4437 daigle
    	 logMetacat.debug("Connection pool size: " +connectionPoolSize);
689
    	 logMetacat.debug("Free Connection number: "+freeConnectionSize);
690 2714 sgarg
     }
691 1219 tao
692
     //If all connections are free and connection pool size greater than
693
     //initial value, shrink connection pool size to intital value
694
     if (difference == 0 && connectionPoolSize > INITIALCONNECTIONNUMBER)
695
     {
696 1220 tao
       //db connection having index from  to connectionpoolsize -1
697
       //intialConnectionnumber should be close and remove from pool
698
       for ( int i=connectionPoolSize-1; i >= INITIALCONNECTIONNUMBER ; i--)
699 1219 tao
       {
700 1220 tao
701 1219 tao
         //get the dbconnection from pool
702
         conn = (DBConnection) connectionPool.elementAt(i);
703
704
         try
705
         {
706 1220 tao
           //close conn
707 1219 tao
           conn.close();
708
         }//try
709
         catch (SQLException e)
710 1220 tao
         {
711
           // set hadException ture
712
           hasException = true;
713 2663 sgarg
           logMetacat.error("Couldn't close a DBConnection in " +
714 1220 tao
                            "DBConnectionPool.shrinkDBConnectionPoolSize: " +
715 2663 sgarg
                            e.getMessage());
716 1219 tao
         }//catch
717 1220 tao
718
        //remove it from pool
719
        connectionPool.remove(i);
720
        // becuase enter the loop, set result true
721
        result = true;
722 1219 tao
       }//for
723
     }//if
724 1220 tao
725
     //if hasException is true ( there at least once exception happend)
726
     // the result should be false
727
     if (hasException)
728
     {
729
       result =false;
730
     }//if
731
     // return result
732
     return result;
733 1219 tao
  }//shrinkDBConnectionPoolSize
734 1220 tao
735
    /**
736
   * Method to decrease dbconnection pool size when all dbconnections are idle
737
   * If all connections are free and connection pool size greater than
738
   * initial value, shrink connection pool size to intital value
739
   */
740
  public static synchronized void shrinkDBConnectionPoolSize()
741
  {
742
     int connectionPoolSize = 0; //store the number of dbconnection pool size
743
     int freeConnectionSize = 0; //store the number of free dbconnection in pool
744
     int difference = 0; // store the difference number between connection size
745
                         // and free connection
746
747
     DBConnection conn = null; // the dbconnection
748
     connectionPoolSize = connectionPool.size();
749
     freeConnectionSize = getFreeDBConnectionNumber();
750
     difference = connectionPoolSize - freeConnectionSize;
751 2716 sgarg
752
     if(freeConnectionSize < connectionPoolSize){
753
         logMetacat.warn(difference + " connection(s) " +
754
                        "being used and connection pool size is " +connectionPoolSize);
755
     } else {
756 4437 daigle
         logMetacat.debug("Connection pool size: " +connectionPoolSize);
757
         logMetacat.debug("Free Connection number: "+freeConnectionSize);
758 2716 sgarg
     }
759 1219 tao
760 1220 tao
     //If all connections are free and connection pool size greater than
761
     //initial value, shrink connection pool size to intital value
762
     if (difference == 0 && connectionPoolSize > INITIALCONNECTIONNUMBER)
763
     {
764
       //db connection having index from  to connectionpoolsize -1
765
       //intialConnectionnumber should be close and remove from pool
766
       for ( int i=connectionPoolSize-1; i >= INITIALCONNECTIONNUMBER ; i--)
767
       {
768
769
         //get the dbconnection from pool
770
         conn = (DBConnection) connectionPool.elementAt(i);
771
         //make sure again the DBConnection status is free
772
         if (conn.getStatus()==FREE)
773
         {
774
           try
775
           {
776
             //close conn
777
             conn.close();
778
           }//try
779
           catch (SQLException e)
780
           {
781
782 2663 sgarg
             logMetacat.error("Couldn't close a DBConnection in " +
783 1220 tao
                            "DBConnectionPool.shrinkDBConnectionPoolSize: " +
784 2663 sgarg
                            e.getMessage());
785 1220 tao
           }//catch
786
787
           //remove it from pool
788
           connectionPool.remove(i);
789
         }//if
790
791
       }//for
792
     }//if
793
794
795
  }//shrinkDBConnectionPoolSize
796 1219 tao
797
798 1087 tao
}//DBConnectionPool