SlideShare a Scribd company logo
1 of 28
Download to read offline
Commons Pool and DBCP

        Phil Steitz
    Apachecon US, 2010
Agenda
• Pool and DBCP at 50,000 ft
• What configuration parameters mean
• Handling different kinds of workloads
• Development roadmap
• Getting involved




                   2
Pool and DBCP
• Born around the same time as Commons itself (spring, 2001)
• DBCP provides the database connection pool for Tomcat
• Pool provides the underlying object pool for DBCP
  – GenericObjectPool             Connections
  – GenericKeyedObjectPool Statements
• Current latest release versions (as of November, 2010)
  – Commons Pool 1.5.5
  – Commons DBCP 1.3 (JDBC 3) and DBCP 1.4 (JDBC 4)




                           3
Pool Features
• Simple object pool and instance factory
  interfaces (being “generified” in 2.0)
• Multiple pool implementations
• Most widely used impl is GenericObjectPool
  –   really works as idle instance pool
  –   configurable maintenance thread
  –   maxActive, maxIdle, minIdle control
  –   maxWait, whenExhaustedAction configurable
  –   instance validation on borrow, return, while idle
  –   LIFO / FIFO behavior configurable




                                 4
Pool Features (cont.)
• StackObjectPool
  – FIFO behavior, simple instance stack
  – No limit to instances in circulation

• SoftReferenceObjectPool
  – Pools soft references
  – No limit to instances in circulation
• KeyedObjectPools
  – GenericKeyedObjectPool
  – StackKeyedObjectPool
• PoolUtils


                            5
DBCP Features
• Pool-backed DataSource implementations
  – BasicDataSource
  – PoolingDataSource
  – BasicManagedDataSource
  – SharedPoolDataSource

• Statement pooling
• Abandoned connection cleanup
• Connection validation
• “Eviction” of connections idle too long in the pool


                          6
DBCP Features (cont)
• Support for JDBC 3 (JDK 1.4-1.5) and JDBC 4
  (JDK 1.6)
  – DBCP 1.3.x implements JDBC 3
  – DBCP 1.4.x implements JDBC 4
  – Incompatibilities between JDBC 3 and 4 APIs have
    forced split in 1.x version sequence
• Creates JDBC connections using Driver-
  DriverManager- and DataSource-based physical
  ConnectionFactories
• Can expose connection pool via a Driver that can
  be registered and accessed using DriverManager



                           7
GenericObjectPool Configuration
 Property                  Meaning                      Default              Notes

            Maximum number of object instances in
maxActive                                                   8       Negative means unlimited
            circulation (idle or checked out)


                                                                    Negative means unlimited
            The maximum number of instances that
maxIdle                                                     8       Enforced when instances
            can be idle in the pool
                                                                    are returned to the pool


                                                                    Negative means unlimited
            The maximum amount of time that
maxWait     borrowObject will wait for an instance to   Unlimited   Only meaningful if
            become available for checkout                           exhaustedAction is
                                                                    BLOCK


                                                                    Enforced only when pool
            The number of idle instances that the                   maintenance thread runs
minIdle                                                     0
            pool will try to keep available
                                                                    Limited by maxActive




                                         8
GenericObjectPool Configuration (cont.)
            Property                       Meaning                   Default             Notes
                                 Action to take when no
                                                                                 BLOCK enables
whenExhaustedAction              instance is available to            BLOCK
                                                                                 maxWait
                                 borrow

                                 Time between pool                               idle instance eviction,
timeBetweenEvictionRunsMillis    maintenance runs in                never runs   minIdle, testWhileIdle
                                 milliseconds                                    require this > 0

                                 The number of milliseconds                      Eviction only happens
                                 that an instance can sit idle in                when the maintenance
minEvictableIdleTimeMillis                                          30 minutes
                                 the pool before being eligible                  thread runs and visits
                                 to be destroyed                                 the instance


                                 Like minEvictableIdleTime                       Enforced only when
                                 but with the additional                         pool maintenance
softMinEvictableIdleTimeMillis   requirement that there are at          0        thread runs
                                 least minIdle instances in the                  Superseded by
                                 pool at idle timeout                            minEvictableIdleTime

                                 The maximum number of idle
                                 instances that the                              Cycles through the
numTestsPerEvictionRun                                                  3
                                 maintenance thread will visit                   pool across runs
                                 when it runs



                                            9
GenericObjectPool Configuration (cont.)
    Property                  Meaning                  Default             Notes

                 Use the object factory’s validate               Failing instances are
 testOnBorrow    method to test instances retrieved    FALSE     destroyed; borrow is retried
                 from the pool                                   until pool is exhausted

                 Validate instances before returning             Failing instances are
 testOnReturn                                          FALSE
                 them to the pool                                destroyed

                                                                 Only meaningful if pool
                 Test idle instances visited by the              maintenance is enabled
 testWhileIdle   pool maintenance thread and           FALSE     (i.e.
                 destroy any that fail validation                timeBetweenEvictionRuns
                                                                 is positive)



                                                                 FALSE means pool
 lifo            Pool behaves as a LIFO queue           TRUE
                                                                 behaves as a LIFO queue




                                           10
Simple Example

                                                     Threads using
numActive = 3                                          borrowed
 numIdle = 6                                           instances
   means                                             numActive = 3
maxActive >= 9




                                               numIdle = 6
                                               maxIdle >= 6



          Instance being validated by maintenance thread
         testWhileIdle = true, timeBetweenEvictionRuns > 0


                            11
Situations to Avoid
maxIdle << maxActive
If active count regularly grows to near maxActive, setting maxIdle too
small will result in lots of object churn (destroy on return, create on
demand)

maxIdle too close to minIdle with frequent
maintenance
Results in object churn as the pool struggles to keep the idle instance
count in a narrow range

Too frequent maintenance
Maintenance thread can contend with client threads for pool and
instance access

Poorly performing factory methods
Especially applies to validation methods if testOnBorrow, testOnReturn
and / or testWhileIdle are enabled



                                12
BasicDataSource Configuration
              Property                      Meaning                             Notes

maxActive, maxIdle, minIdle,
maxWait, testOnBorrow,
                                 Same meanings and defaults         whenExhaustedAction is
testOnReturn, testWhileIdle,
                                 as pool                            BLOCK
timeBetweenEvictionRunsMillis,
numTestsPerEvictionRun
                                 Number of connections created
                                                                    Cannot exceed the maxActive
initialSize                      and placed into the pool on
                                                                    pool property
                                 initialization
defaultAutoCommit
                                                                    Clients can change these
defaultCatalog
                                 properties of connections          properties on checked out
defaultReadOnly
                                 provided by this DataSource        connections; but the value is
defaultTransactionIsolation
                                                                    reset to default on passivation
connectionProperties

                                 fully qualified class name of
                                                                    Must be available on the
driverClassName                  JDBC Driver used to manage
                                                                    classpath at runtime
                                 physical connections

url                              JDBC connection parameters         If set, username and password
username                         shared by all connections in the   supersede values in
password                         pool                               connectionProperties




                                          13
BasicDataSource Configuration (cont.)
           Property                    Meaning                              Notes

                            SQL Query used to validate         Validation succeeds iff this
validationQuery                                                query returns at least one row;
                            connections
                                                               testOnBorrow, testOnReturn,
                                                               testWhileIdle are ignored if
validationQueryTimeout      Timeout for validation queries     validationQuery is null



                            Initialization SQL executed once   If any of the statements in the
connectInitSQLs             when a connection is first         list throw exceptions, the
                            created                            connection is destroyed


                                                               Pooling PreparedStatements
                            true means a prepared statement
                                                               may keep their cursors open in
poolPreparedStatements      pool is created for each
                                                               the database, causing a
                            connection
                                                               connection to run out of cursors

                            maximum number of prepared
maxOpenPreparedStatements   statements that can be pooled      Default is unlimited
                            per connection




                                      14
BasicDataSource Configuration (cont.)
            Property                 Meaning                            Notes

                                                             Abandoned connection removal
                         True means the pool will try to     is triggered when a connection
removeAbandoned          identify and remove “abandoned”     is requested and
                         connections
                                                             numIdle < 2 and
                                                             numActive > maxActive - 3

                                                             Connections are considered
                         True means stack traces for the     abandoned if they have not
logAbandoned             code opening “abandoned”            been used (via JDBC
                         connections will be logged          operations) in more than
                                                             removeAbandonedTimeout
                                                             seconds

                         The amount of time between          Default value is 300 seconds;
removeAbandonedTimeout   uses of a connection before it is   ignored if removeAbandoned is
                         considered “abandoned.”             false

                         PrintWriter used to log
logWriter
                         abandoned connection info




                                    15
Configuration Example
DBCP Using BasicDataSource
Application code “leaks” connections on some exception paths
Database times out and closes connections after 60 minutes of inactivity
Load varies from non-existent (off hours) to 100 hits / second spikes
during peak; ramp begins around 6AM local time, peaking around 11AM,
diminishing around 2-3PM
Peak load can be handled (sustained) with 100 database connections

Configuration Considerations
Eliminating connection leaks is much better than relying on abandoned
connection cleanup. Even with this configured, spikes in “leaky”
execution paths will cause connection churn and pool exhaustion.
Setting testOnBorrow will ensure connections timed out on the server
side are not returned to clients; testWhileIdle will remove these before
they are checked out (and also keep them alive if frequent enough)




                               16
Configuration Example (cont.)
Simplest option
Assumptions:
    • Connection leaks can be removed
    • You can afford to allocate 100 database connections to the app
                                Set maxIdle to 50 to
Configuration Settings:         reduce connections        If connection leaks cannot
                                reserved - cost is        be closed, set
 maxActive = 100                connection churn          removeAbandoned = true
 maxIdle = 100                                            and configure timeout to
                                                          be greater than longest
 testOnBorrow = true           validate connections
                                                          running query
                               when borrowed
 testOnReturn = false
 testWhileIdle = false              Set to true and turn on
 removeAbandoned = false            maintenance to keep idle
                                    connections alive in the pool
 poolPreparedStatements = false
 timeBetweenEvictionRunsMillis = -1




                                    17
Configuration Example (cont.)
If leaks can’t be closed (or are FIX_LATER)
 •    Estimate peak incidence rate (how many per unit time)
 •    Estimate longest running query time
 •    If maxActive / (peak incidence rate) < (max query time) you are SOL
 •    In fact, you need >> above to not be SOL
 •    If not SOL, configuring abandoned connection cleanup can help
Configuration Settings:
 removeAbandoned = true
 removeAbandonedTimeout > longest running query time (in seconds)

NOTE:
 Abandoned connection cleanup must be triggered by a getConnection()
 request
     ➡ All threads can block until a new thread arrives to trigger cleanup
       (JIRA: DBCP-260)


                                    18
Configuration Example (cont.)
Handling server-side connection timeouts
 • Nothing you can do if clients check out and hold connections beyond
     server-side timeout (other than close them as abandoned)
 •   Three ways to handle preventing stale connections from being
     returned by getConnection()
     1. Set testOnBorrow = true
     2. Enable pool maintenance, set minEvictableIdleTimeMillis < server
        side timeout (in ms)
     3. Enable pool maintenance, set testWhileIdle = true and ensure
        connections are visited frequently enough to avoid timeout
 •




     Practical considerations
     ‣ Once physical connections are closed on the server side,
        validation query may hang
     ‣ When using options 2 or 3 above, make sure to set
        numTestsPerEvictionRun and timeBetweenEvictionRunsMillis so
        that connections are visited frequently enough



                                 19
Conserving Pooled Resources
    Trimming idle instance pool when load subsides
    Two ways to reduce “idleness”
        1. Set maxIdle < maxActive
        2. Enable pool maintenance, set minEvictableIdleTimeMillis > 0
•




    Practical considerations
       ‣ MaxIdle is enforced when instances are returned to the pool
       ‣ Oscillating load and maxIdle << maxActive can lead to a lot of
           object churn
       ‣ Running pool maintenance too frequently can lead to performance
           problems
       ‣ If maintenance is enabled and minIdle is set close to maxIdle,
           object churn will result
       ‣ If instance creation is slow and load spikes are sudden, new
           instance creation in a trimmed pool can cause performance
           problems



                                    20
Simple Config Code
BasicDataSource ds = new BasicDataSource();                    Driver class must exist
                                                               on classpath
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///test");
ds.setUsername("username");           All new connections created
                                      this way and reset to this value
ds.setPassword("password");
                                      before being reused
ds.setDefaultAutoCommit(false);

ds.setMaxActive(50);
                                          ds.getConnection() will timeout and
ds.setMaxIdle(50);                        throw SQLException after 10 seconds
ds.setMaxWait(10000);

ds.setTestWhileIdle(true);
ds.setTestOnBorrow(true);
ds.setTestOnReturn(false);
ds.setValidationQuery("SELECT 1");

ds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 15);
ds.setMinEvictableIdleTimeMillis(1000 * 60 * 2);
ds.setNumTestsPerEvictionRun(10);

ds.setRemoveAbandoned(true);
ds.setRemoveAbandonedTimeout(60 * 60);        Connections that have not been used in
ds.setLogAbandoned(true);                     more than one hour may be closed




                                     21
“Manual” setup using PoolingDataSource

GenericObjectPool pool = new GenericObjectPool();
pool.setMaxActive(15);
                                         Manually create GOP used to manage
pool.setMaxIdle(15);                     connections - can set properties not
pool.setMaxWait(10000);                  exposed by BasicDataSource this way

Properties props = new Properties();
props.setProperty("user", "username");       Manually create object factory and
                                           associate it with the pool -
props.setProperty("password", "password");
                                           BasicDataSource does this on first
PoolableConnectionFactory factory =         getConnection() request
    new PoolableConnectionFactory(
        new DriverConnectionFactory(new TesterDriver(),
                "com.mysql.jdbc.Driver", props),
        pool, null, "SELECT 1", true, true);
pool.setFactory(factory);
ds = new PoolingDataSource(pool);




                                      22
Simulations
    Using Commons Performance (Commons “Sandbox” component)
      http://commons.apache.org/sandbox/performance

    Effect of maxIdle << maxActive under oscillating load
                                       No Idle Throttling                Idle Throttling
maxIdle                           34                                10

mean response latency             35.78 ms                          49.58 ms

std dev response latency          5.19 ms                           33.54 ms

mean instance idle time           34.07 ms                          17.87 ms

maxActive                 34                       client threads              100
exhausted action          block, no timeout        min delay                   100 ms
pool maintenance          off                      max delay                   1 second
Instance validation       on borrow only           ramp type                   linear
make latency              100 ms                   ramp period                 500 ms
destroy latency           0                        peak period                 3 seconds
validate latency          10 ms                    trough period               2 seconds
client hold time          25 ms                    iterations                  10000
                                              23
Simulations (cont.)
    Effect of Abandoned Connection Cleanup
                              No abandonment        0.001 abandon rate   0.01 abandon rate

mean response latency         7.0 ms                7.57 ms              336.7 ms

std dev response latency      11.4 ms               12.90 ms             2461.9 ms



 maxActive              15                          client threads       90
 maxIdle                15                          min delay            250 ms
 exhausted action       block, no timeout           max delay            1 second

 pool maintenance       off                         ramp type            linear
                                                    ramp period          20 seconds
 instance validation    on borrow only
                                                    peak period          100 seconds
 query type             text scan
                                                    trough period        20 seconds
 client threads         90
                                                    iterations           10000
 peak load              4 requests / client / sec
 minimum load           1 request / client / sec




                                            24
Simulations (cont.)
                          Effect of Old Pool version
                                          Pool 1.5.5                     Pool 1.3

mean response latency             35.78 ms                     986.22 ms


std dev response latency          5.19 ms                      3766.4 ms


mean instance idle time           34.07 ms                     10.2 ms


maxActive             34                       client threads            100
maxIdle               10                       min delay                 100 ms
exhausted action      block, no timeout        max delay                 1 second
pool maintenance      off                      ramp type                 linear
Instance validation   on borrow only           ramp period               500 ms
make latency          100 ms                   peak period               3 seconds
destroy latency       0                        trough period             2 seconds
validate latency      10 ms                    iterations                10000
client hold time      25 ms



                                             25
Roadmap                              Pool and DBCP
                                     Modernize API
      Pool                            – Generification
                                      – JMX
Modernize Implementation              – Fix sins of the past
– Replace wait/notify with JDK
  1.5 concurrency
                                          DBCP
– Integrate Tomcat jdbc-pool
Improve Operational
                                 •




                                     Improve Robustness
Control                              – Server / Connection
                                       Failures
– Instance management
                                     – Exception Management
– Idle instance count
  management


                          26
Roadmap (cont.)
• 2.0 Versions will break backward compatibility
  and require JDK 1.5+
• 1.x releases will be bugfix only
• Code will be repackaged as
  org.apache.commons.pool2 / dbcp2
• API refactoring has begun in svn trunk
• Patches welcome!




                        27
Get Involved!
1. Subscribe to Commons-dev
    http://commons.apache.org/mail-lists.html
2. Check out the code
    http://commons.apache.org/svninfo.html
3. Review open issues
    http://commons.apache.org/pool/issue-tracking.html
4. Talk about your ideas
5. Attach patches to JIRA tickets
   http://commons.apache.org/patches.html
6. THANKS!!

                         28

More Related Content

What's hot

Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Ryan Cuprak
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQLRoberto Franchini
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능knight1128
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On ConcurrencyRodney Barlow
 
Effective out-of-container Integration Testing
Effective out-of-container Integration TestingEffective out-of-container Integration Testing
Effective out-of-container Integration TestingSam Brannen
 
Pitfalls of Continuous Deployment
Pitfalls of Continuous DeploymentPitfalls of Continuous Deployment
Pitfalls of Continuous Deploymentzeeg
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkVijay Nair
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionAntonio Goncalves
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3JavaEE Trainers
 

What's hot (20)

Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
 
Servlets
ServletsServlets
Servlets
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On Concurrency
 
Effective out-of-container Integration Testing
Effective out-of-container Integration TestingEffective out-of-container Integration Testing
Effective out-of-container Integration Testing
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Pitfalls of Continuous Deployment
Pitfalls of Continuous DeploymentPitfalls of Continuous Deployment
Pitfalls of Continuous Deployment
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Hazelcast
HazelcastHazelcast
Hazelcast
 

Viewers also liked

Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdatePhil Steitz
 
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTER
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTERREPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTER
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTEREduardo Schenker
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
深入淺出 Web 容器 - Tomcat 原始碼分析
深入淺出 Web 容器  - Tomcat 原始碼分析深入淺出 Web 容器  - Tomcat 原始碼分析
深入淺出 Web 容器 - Tomcat 原始碼分析Justin Lin
 
Big Java, Big Data
Big Java, Big DataBig Java, Big Data
Big Java, Big DataKuo-Chun Su
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2WASH United
 
Difrentiation
DifrentiationDifrentiation
Difrentiationlecturer
 
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries Limited
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries LimitedKankroli Tyre Plant(KTP), A unit of JK Tyre & Industries Limited
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries LimitedIndia Water Portal
 
Openstack 101 by Jason Kalai
Openstack 101 by Jason KalaiOpenstack 101 by Jason Kalai
Openstack 101 by Jason KalaiMyNOG
 
Step Up 1 and 2 ppt
Step Up 1 and 2 pptStep Up 1 and 2 ppt
Step Up 1 and 2 pptguestcef88d
 
Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is S K "Bal" Palekar
 
Kode etik jurnalistik ifj penafsiran dan praktik
Kode etik jurnalistik ifj penafsiran dan praktikKode etik jurnalistik ifj penafsiran dan praktik
Kode etik jurnalistik ifj penafsiran dan praktikTeras Lampung
 

Viewers also liked (20)

Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
 
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTER
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTERREPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTER
REPORTE INSTALACIÓN Y CONFIGURACIÓN DEL MySQL CLUSTER
 
Commons Nabla
Commons NablaCommons Nabla
Commons Nabla
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
深入淺出 Web 容器 - Tomcat 原始碼分析
深入淺出 Web 容器  - Tomcat 原始碼分析深入淺出 Web 容器  - Tomcat 原始碼分析
深入淺出 Web 容器 - Tomcat 原始碼分析
 
Big Java, Big Data
Big Java, Big DataBig Java, Big Data
Big Java, Big Data
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2
 
Caliac disease
Caliac diseaseCaliac disease
Caliac disease
 
Difrentiation
DifrentiationDifrentiation
Difrentiation
 
Final oral test
Final oral testFinal oral test
Final oral test
 
Attom
AttomAttom
Attom
 
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries Limited
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries LimitedKankroli Tyre Plant(KTP), A unit of JK Tyre & Industries Limited
Kankroli Tyre Plant(KTP), A unit of JK Tyre & Industries Limited
 
Hgfhfh
HgfhfhHgfhfh
Hgfhfh
 
Openstack 101 by Jason Kalai
Openstack 101 by Jason KalaiOpenstack 101 by Jason Kalai
Openstack 101 by Jason Kalai
 
Step Up 1 and 2 ppt
Step Up 1 and 2 pptStep Up 1 and 2 ppt
Step Up 1 and 2 ppt
 
Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is
 
Kode etik jurnalistik ifj penafsiran dan praktik
Kode etik jurnalistik ifj penafsiran dan praktikKode etik jurnalistik ifj penafsiran dan praktik
Kode etik jurnalistik ifj penafsiran dan praktik
 
Elearning v.0.0
Elearning v.0.0Elearning v.0.0
Elearning v.0.0
 
Versos
VersosVersos
Versos
 

Similar to Commons Pool and DBCP

Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applicationspkoza
 
Cordoba Docker meetup #7: Kubernetes
Cordoba Docker meetup  #7: KubernetesCordoba Docker meetup  #7: Kubernetes
Cordoba Docker meetup #7: KubernetesFranco Ariel Salonia
 
Transactional Memory for Smalltalk
Transactional Memory for SmalltalkTransactional Memory for Smalltalk
Transactional Memory for SmalltalkLukas Renggli
 
Bytebuf vs DirectByteBuffer
Bytebuf vs DirectByteBufferBytebuf vs DirectByteBuffer
Bytebuf vs DirectByteBufferMichael Fong
 
Security Applications For Emulation
Security Applications For EmulationSecurity Applications For Emulation
Security Applications For EmulationSilvio Cesare
 

Similar to Commons Pool and DBCP (9)

Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java ApplicationsEfficient Memory and Thread Management in Highly Parallel Java Applications
Efficient Memory and Thread Management in Highly Parallel Java Applications
 
Kubernetes 101
Kubernetes 101Kubernetes 101
Kubernetes 101
 
Cordoba Docker meetup #7: Kubernetes
Cordoba Docker meetup  #7: KubernetesCordoba Docker meetup  #7: Kubernetes
Cordoba Docker meetup #7: Kubernetes
 
Transactional Memory for Smalltalk
Transactional Memory for SmalltalkTransactional Memory for Smalltalk
Transactional Memory for Smalltalk
 
Bytebuf vs DirectByteBuffer
Bytebuf vs DirectByteBufferBytebuf vs DirectByteBuffer
Bytebuf vs DirectByteBuffer
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Java tips
Java tipsJava tips
Java tips
 
Security Applications For Emulation
Security Applications For EmulationSecurity Applications For Emulation
Security Applications For Emulation
 

Recently uploaded

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Commons Pool and DBCP

  • 1. Commons Pool and DBCP Phil Steitz Apachecon US, 2010
  • 2. Agenda • Pool and DBCP at 50,000 ft • What configuration parameters mean • Handling different kinds of workloads • Development roadmap • Getting involved 2
  • 3. Pool and DBCP • Born around the same time as Commons itself (spring, 2001) • DBCP provides the database connection pool for Tomcat • Pool provides the underlying object pool for DBCP – GenericObjectPool Connections – GenericKeyedObjectPool Statements • Current latest release versions (as of November, 2010) – Commons Pool 1.5.5 – Commons DBCP 1.3 (JDBC 3) and DBCP 1.4 (JDBC 4) 3
  • 4. Pool Features • Simple object pool and instance factory interfaces (being “generified” in 2.0) • Multiple pool implementations • Most widely used impl is GenericObjectPool – really works as idle instance pool – configurable maintenance thread – maxActive, maxIdle, minIdle control – maxWait, whenExhaustedAction configurable – instance validation on borrow, return, while idle – LIFO / FIFO behavior configurable 4
  • 5. Pool Features (cont.) • StackObjectPool – FIFO behavior, simple instance stack – No limit to instances in circulation • SoftReferenceObjectPool – Pools soft references – No limit to instances in circulation • KeyedObjectPools – GenericKeyedObjectPool – StackKeyedObjectPool • PoolUtils 5
  • 6. DBCP Features • Pool-backed DataSource implementations – BasicDataSource – PoolingDataSource – BasicManagedDataSource – SharedPoolDataSource • Statement pooling • Abandoned connection cleanup • Connection validation • “Eviction” of connections idle too long in the pool 6
  • 7. DBCP Features (cont) • Support for JDBC 3 (JDK 1.4-1.5) and JDBC 4 (JDK 1.6) – DBCP 1.3.x implements JDBC 3 – DBCP 1.4.x implements JDBC 4 – Incompatibilities between JDBC 3 and 4 APIs have forced split in 1.x version sequence • Creates JDBC connections using Driver- DriverManager- and DataSource-based physical ConnectionFactories • Can expose connection pool via a Driver that can be registered and accessed using DriverManager 7
  • 8. GenericObjectPool Configuration Property Meaning Default Notes Maximum number of object instances in maxActive 8 Negative means unlimited circulation (idle or checked out) Negative means unlimited The maximum number of instances that maxIdle 8 Enforced when instances can be idle in the pool are returned to the pool Negative means unlimited The maximum amount of time that maxWait borrowObject will wait for an instance to Unlimited Only meaningful if become available for checkout exhaustedAction is BLOCK Enforced only when pool The number of idle instances that the maintenance thread runs minIdle 0 pool will try to keep available Limited by maxActive 8
  • 9. GenericObjectPool Configuration (cont.) Property Meaning Default Notes Action to take when no BLOCK enables whenExhaustedAction instance is available to BLOCK maxWait borrow Time between pool idle instance eviction, timeBetweenEvictionRunsMillis maintenance runs in never runs minIdle, testWhileIdle milliseconds require this > 0 The number of milliseconds Eviction only happens that an instance can sit idle in when the maintenance minEvictableIdleTimeMillis 30 minutes the pool before being eligible thread runs and visits to be destroyed the instance Like minEvictableIdleTime Enforced only when but with the additional pool maintenance softMinEvictableIdleTimeMillis requirement that there are at 0 thread runs least minIdle instances in the Superseded by pool at idle timeout minEvictableIdleTime The maximum number of idle instances that the Cycles through the numTestsPerEvictionRun 3 maintenance thread will visit pool across runs when it runs 9
  • 10. GenericObjectPool Configuration (cont.) Property Meaning Default Notes Use the object factory’s validate Failing instances are testOnBorrow method to test instances retrieved FALSE destroyed; borrow is retried from the pool until pool is exhausted Validate instances before returning Failing instances are testOnReturn FALSE them to the pool destroyed Only meaningful if pool Test idle instances visited by the maintenance is enabled testWhileIdle pool maintenance thread and FALSE (i.e. destroy any that fail validation timeBetweenEvictionRuns is positive) FALSE means pool lifo Pool behaves as a LIFO queue TRUE behaves as a LIFO queue 10
  • 11. Simple Example Threads using numActive = 3 borrowed numIdle = 6 instances means numActive = 3 maxActive >= 9 numIdle = 6 maxIdle >= 6 Instance being validated by maintenance thread testWhileIdle = true, timeBetweenEvictionRuns > 0 11
  • 12. Situations to Avoid maxIdle << maxActive If active count regularly grows to near maxActive, setting maxIdle too small will result in lots of object churn (destroy on return, create on demand) maxIdle too close to minIdle with frequent maintenance Results in object churn as the pool struggles to keep the idle instance count in a narrow range Too frequent maintenance Maintenance thread can contend with client threads for pool and instance access Poorly performing factory methods Especially applies to validation methods if testOnBorrow, testOnReturn and / or testWhileIdle are enabled 12
  • 13. BasicDataSource Configuration Property Meaning Notes maxActive, maxIdle, minIdle, maxWait, testOnBorrow, Same meanings and defaults whenExhaustedAction is testOnReturn, testWhileIdle, as pool BLOCK timeBetweenEvictionRunsMillis, numTestsPerEvictionRun Number of connections created Cannot exceed the maxActive initialSize and placed into the pool on pool property initialization defaultAutoCommit Clients can change these defaultCatalog properties of connections properties on checked out defaultReadOnly provided by this DataSource connections; but the value is defaultTransactionIsolation reset to default on passivation connectionProperties fully qualified class name of Must be available on the driverClassName JDBC Driver used to manage classpath at runtime physical connections url JDBC connection parameters If set, username and password username shared by all connections in the supersede values in password pool connectionProperties 13
  • 14. BasicDataSource Configuration (cont.) Property Meaning Notes SQL Query used to validate Validation succeeds iff this validationQuery query returns at least one row; connections testOnBorrow, testOnReturn, testWhileIdle are ignored if validationQueryTimeout Timeout for validation queries validationQuery is null Initialization SQL executed once If any of the statements in the connectInitSQLs when a connection is first list throw exceptions, the created connection is destroyed Pooling PreparedStatements true means a prepared statement may keep their cursors open in poolPreparedStatements pool is created for each the database, causing a connection connection to run out of cursors maximum number of prepared maxOpenPreparedStatements statements that can be pooled Default is unlimited per connection 14
  • 15. BasicDataSource Configuration (cont.) Property Meaning Notes Abandoned connection removal True means the pool will try to is triggered when a connection removeAbandoned identify and remove “abandoned” is requested and connections numIdle < 2 and numActive > maxActive - 3 Connections are considered True means stack traces for the abandoned if they have not logAbandoned code opening “abandoned” been used (via JDBC connections will be logged operations) in more than removeAbandonedTimeout seconds The amount of time between Default value is 300 seconds; removeAbandonedTimeout uses of a connection before it is ignored if removeAbandoned is considered “abandoned.” false PrintWriter used to log logWriter abandoned connection info 15
  • 16. Configuration Example DBCP Using BasicDataSource Application code “leaks” connections on some exception paths Database times out and closes connections after 60 minutes of inactivity Load varies from non-existent (off hours) to 100 hits / second spikes during peak; ramp begins around 6AM local time, peaking around 11AM, diminishing around 2-3PM Peak load can be handled (sustained) with 100 database connections Configuration Considerations Eliminating connection leaks is much better than relying on abandoned connection cleanup. Even with this configured, spikes in “leaky” execution paths will cause connection churn and pool exhaustion. Setting testOnBorrow will ensure connections timed out on the server side are not returned to clients; testWhileIdle will remove these before they are checked out (and also keep them alive if frequent enough) 16
  • 17. Configuration Example (cont.) Simplest option Assumptions: • Connection leaks can be removed • You can afford to allocate 100 database connections to the app Set maxIdle to 50 to Configuration Settings: reduce connections If connection leaks cannot reserved - cost is be closed, set maxActive = 100 connection churn removeAbandoned = true maxIdle = 100 and configure timeout to be greater than longest testOnBorrow = true validate connections running query when borrowed testOnReturn = false testWhileIdle = false Set to true and turn on removeAbandoned = false maintenance to keep idle connections alive in the pool poolPreparedStatements = false timeBetweenEvictionRunsMillis = -1 17
  • 18. Configuration Example (cont.) If leaks can’t be closed (or are FIX_LATER) • Estimate peak incidence rate (how many per unit time) • Estimate longest running query time • If maxActive / (peak incidence rate) < (max query time) you are SOL • In fact, you need >> above to not be SOL • If not SOL, configuring abandoned connection cleanup can help Configuration Settings: removeAbandoned = true removeAbandonedTimeout > longest running query time (in seconds) NOTE: Abandoned connection cleanup must be triggered by a getConnection() request ➡ All threads can block until a new thread arrives to trigger cleanup (JIRA: DBCP-260) 18
  • 19. Configuration Example (cont.) Handling server-side connection timeouts • Nothing you can do if clients check out and hold connections beyond server-side timeout (other than close them as abandoned) • Three ways to handle preventing stale connections from being returned by getConnection() 1. Set testOnBorrow = true 2. Enable pool maintenance, set minEvictableIdleTimeMillis < server side timeout (in ms) 3. Enable pool maintenance, set testWhileIdle = true and ensure connections are visited frequently enough to avoid timeout • Practical considerations ‣ Once physical connections are closed on the server side, validation query may hang ‣ When using options 2 or 3 above, make sure to set numTestsPerEvictionRun and timeBetweenEvictionRunsMillis so that connections are visited frequently enough 19
  • 20. Conserving Pooled Resources Trimming idle instance pool when load subsides Two ways to reduce “idleness” 1. Set maxIdle < maxActive 2. Enable pool maintenance, set minEvictableIdleTimeMillis > 0 • Practical considerations ‣ MaxIdle is enforced when instances are returned to the pool ‣ Oscillating load and maxIdle << maxActive can lead to a lot of object churn ‣ Running pool maintenance too frequently can lead to performance problems ‣ If maintenance is enabled and minIdle is set close to maxIdle, object churn will result ‣ If instance creation is slow and load spikes are sudden, new instance creation in a trimmed pool can cause performance problems 20
  • 21. Simple Config Code BasicDataSource ds = new BasicDataSource(); Driver class must exist on classpath ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql:///test"); ds.setUsername("username"); All new connections created this way and reset to this value ds.setPassword("password"); before being reused ds.setDefaultAutoCommit(false); ds.setMaxActive(50); ds.getConnection() will timeout and ds.setMaxIdle(50); throw SQLException after 10 seconds ds.setMaxWait(10000); ds.setTestWhileIdle(true); ds.setTestOnBorrow(true); ds.setTestOnReturn(false); ds.setValidationQuery("SELECT 1"); ds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 15); ds.setMinEvictableIdleTimeMillis(1000 * 60 * 2); ds.setNumTestsPerEvictionRun(10); ds.setRemoveAbandoned(true); ds.setRemoveAbandonedTimeout(60 * 60); Connections that have not been used in ds.setLogAbandoned(true); more than one hour may be closed 21
  • 22. “Manual” setup using PoolingDataSource GenericObjectPool pool = new GenericObjectPool(); pool.setMaxActive(15); Manually create GOP used to manage pool.setMaxIdle(15); connections - can set properties not pool.setMaxWait(10000); exposed by BasicDataSource this way Properties props = new Properties(); props.setProperty("user", "username"); Manually create object factory and associate it with the pool - props.setProperty("password", "password"); BasicDataSource does this on first PoolableConnectionFactory factory = getConnection() request new PoolableConnectionFactory( new DriverConnectionFactory(new TesterDriver(), "com.mysql.jdbc.Driver", props), pool, null, "SELECT 1", true, true); pool.setFactory(factory); ds = new PoolingDataSource(pool); 22
  • 23. Simulations Using Commons Performance (Commons “Sandbox” component) http://commons.apache.org/sandbox/performance Effect of maxIdle << maxActive under oscillating load No Idle Throttling Idle Throttling maxIdle 34 10 mean response latency 35.78 ms 49.58 ms std dev response latency 5.19 ms 33.54 ms mean instance idle time 34.07 ms 17.87 ms maxActive 34 client threads 100 exhausted action block, no timeout min delay 100 ms pool maintenance off max delay 1 second Instance validation on borrow only ramp type linear make latency 100 ms ramp period 500 ms destroy latency 0 peak period 3 seconds validate latency 10 ms trough period 2 seconds client hold time 25 ms iterations 10000 23
  • 24. Simulations (cont.) Effect of Abandoned Connection Cleanup No abandonment 0.001 abandon rate 0.01 abandon rate mean response latency 7.0 ms 7.57 ms 336.7 ms std dev response latency 11.4 ms 12.90 ms 2461.9 ms maxActive 15 client threads 90 maxIdle 15 min delay 250 ms exhausted action block, no timeout max delay 1 second pool maintenance off ramp type linear ramp period 20 seconds instance validation on borrow only peak period 100 seconds query type text scan trough period 20 seconds client threads 90 iterations 10000 peak load 4 requests / client / sec minimum load 1 request / client / sec 24
  • 25. Simulations (cont.) Effect of Old Pool version Pool 1.5.5 Pool 1.3 mean response latency 35.78 ms 986.22 ms std dev response latency 5.19 ms 3766.4 ms mean instance idle time 34.07 ms 10.2 ms maxActive 34 client threads 100 maxIdle 10 min delay 100 ms exhausted action block, no timeout max delay 1 second pool maintenance off ramp type linear Instance validation on borrow only ramp period 500 ms make latency 100 ms peak period 3 seconds destroy latency 0 trough period 2 seconds validate latency 10 ms iterations 10000 client hold time 25 ms 25
  • 26. Roadmap Pool and DBCP Modernize API Pool – Generification – JMX Modernize Implementation – Fix sins of the past – Replace wait/notify with JDK 1.5 concurrency DBCP – Integrate Tomcat jdbc-pool Improve Operational • Improve Robustness Control – Server / Connection Failures – Instance management – Exception Management – Idle instance count management 26
  • 27. Roadmap (cont.) • 2.0 Versions will break backward compatibility and require JDK 1.5+ • 1.x releases will be bugfix only • Code will be repackaged as org.apache.commons.pool2 / dbcp2 • API refactoring has begun in svn trunk • Patches welcome! 27
  • 28. Get Involved! 1. Subscribe to Commons-dev http://commons.apache.org/mail-lists.html 2. Check out the code http://commons.apache.org/svninfo.html 3. Review open issues http://commons.apache.org/pool/issue-tracking.html 4. Talk about your ideas 5. Attach patches to JIRA tickets http://commons.apache.org/patches.html 6. THANKS!! 28