Sie sind auf Seite 1von 34

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

c3p0-JDBC3ConnectionandStatement Pooling
version0.9.1.1 bySteveWaldman<swaldman@mchange.com> 2006MachineryForChange,Inc. Thissoftwareismadeavailableforuse,modification,and redistribution,underthetermsoftheLesserGNUPublicLicense (LGPL),whichyoushouldhavereceivedwiththisdistribution. APIdocsforc3p0arehere. Downloadthelatestversionfromc3p0'ssiteonSourceForge Lookingforthedefinitionofconfigurationproperties? Lookingforadviceinusingc3p0withhibernate?

Contents
1. 2. 3. 4. 5. 6. Contents Quickstart Whatisc3p0? Prerequisites Installation Usingc3p0
i. UsingComboPooledDataSource ii. UsingtheDataSoucesfactoryclass Box:Overridingauthenticationinformation(fromnon-c3p0DataSources) iii. QueryingPoolStatus Box:UsingC3P0RegistrytofindareferencetoaDataSource iv. CleaningUpPoolResources v. Advanced:BuildingYourOwnPoolBackedDataSource vi. Advanced:RawConnectionandStatementOperations

7. Configuration
i. ii. iii. iv. v. vi. vii. viii. ix. x. xi. Introduction BasicPoolConfiguration ManagingPoolSizeandConnectionAge ConfiguringConnectionTesting ConfiguringStatementPooling ConfiguringRecoveryFromDatabaseOutages ManagingConnectionLifecycleswithConnectionCustomizers ConfiguringUnresolvedTransactionHandling ConfiguringtoDebugandWorkaroundBrokenClientApplications OtherDataSourceConfiguration ConfiguringandManagingc3p0viaJMX

1 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...


xii. ConfiguringLogging

http://www.mchange.com/projects/c3p0/index.html

8. 9. 10. 11. 12.

Performance Knownshortcomings Feedbackandsupport AppendixA:ConfigurationProperties AppendixB:ConfiguationFiles,etc.


i. ii. iii. iv. Overridingc3p0defaultswithac3p0.propertiesfile Overridingc3p0defaultswithaSystemproperties NamedandPer-Userconfiguration:Overridingc3p0defaultsviac3p0-config.xml PrecedenceofConfigurationSettings

13. 14. 15. 16.

AppendixC:Hibernate-specificnotes AppendixD:Configuringc3p0pooledDataSourcesforApacheTomcat AppendixE:JBoss-specificnotes AppendixF:Oracle-specificAPI:createTemporaryBLOB()andcreateTemporaryCLOB()

(SeealsotheAPIDocumentationhere)

Quickstart
c3p0wasdesignedtobebutt-simpletouse.Justputthejarfile[lib/c3p0-0.9.1.1.jar]inyour application'seffectiveCLASSPATH,andmakeaDataSourcelikethis:

import com.mchange.v2.c3p0.*; ... ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" ); cpds.setUser("dbuser"); cpds.setPassword("dbpassword");

[Optional]IfyouwanttoturnonPreparedStatementpooling,youmustalsosetmaxStatements and/ormaxStatementsPerConnection(bothdefaultto0):

cpds.setMaxStatements( 180 );

DowhateveryouwantwithyourDataSource,whichwillbebackedbyaConnectionpoolset upwithdefaultparameters.YoucanbindtheDataSourcetoaJNDInameservice,oruseit directly,asyouprefer. Whenyouaredone,youcancleanuptheDataSourceyou'vecreatedlikethis:

2 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

DataSources.destroy( cpds );

That'sit!Therestisdetail.

Whatisc3p0?
c3p0isaneasy-to-uselibraryformakingtraditionalJDBCdrivers"enterprise-ready"by augmentingthemwithfunctionalitydefinedbythejdbc3specandtheoptionalextensionsto jdbc2.Inparticular,c3p0providesseveralusefulservices: ClasseswhichadapttraditionalDriverManager-basedJDBCdriverstothenew javax.sql.DataSourceschemeforacquiringdatabaseConnections. TransparentpoolingofConnectionandPreparedStatementsbehindDataSources whichcan"wrap"aroundtraditionaldriversorarbitraryunpooledDataSources. Thelibrarytrieshardtogetthedetailsright: c3p0DataSourcesarebothReferenceableandSerializable,andarethussuitablefor bindingtoawide-varietyofJNDI-basednamingservices. StatementandResultSetsarecarefullycleanedupwhenpooledConnectionsand Statementsarecheckedin,topreventresource-exhaustionwhenclientsusethelazy butcommonresource-managementstrategyofonlycleaninguptheirConnections.... ThelibraryadoptstheapproachdefinedbytheJDBC2and3specification(evenwhere theseconflictwiththelibraryauthor'spreferences).DataSourcesarewritteninthe JavaBeanstyle,offeringalltherequiredandmostoftheoptionalproperties(aswellas somenon-standardones),andno-argconstructors.AllJDBC-definedinternalinterfaces areimplemented(ConnectionPoolDataSource,PooledConnection,ConnectionEventgeneratingConnections,etc.)Youcanmixc3p0classeswithcompliantthird-party implementations(althoughnotallc3p0featureswillworkwithexternal implementations). c3p0hopestoprovideDataSourceimplementationsmorethansuitableforuseby high-volume"J2EEenterpriseapplications".Pleaseprovidefeedback,bug-fixes,etc.!

Prerequisites
c3p0requiresalevel1.3.xoraboveJavaRuntimeEnvironment,andtheJDBC2.xorabove javax.sqllibraries.c3p0worksfineunderJava1.4.xand1.5.xaswell.

3 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Installation
Putthefilelib/c3p0-0.9.1.1.jarsomewhereinyourCLASSPATH(oranyotherplacewhere yourapplication'sclassloaderwillfindit).That'sit!

Usingc3p0
Fromausers'perspective,c3p0simplyprovidesstandardjdbc2DataSourceobjects.When creatingtheseDataSources,userscancontrolpooling-related,naming-related,andother properties(SeeAppendixA).AllpoolingisentirelytransparenttousersonceaDataSource hasbeencreated. Therearethreewaysofacquiringc3p0pool-backedDataSources:1)directlyinstantiateand configureaComboPooledDataSourcebean;2)usetheDataSourcesfactoryclass;or3)"buildyour own"pool-backedDataSourcebydirectlyinstantiatingPoolBackedDataSourceandsettingits ConectionPoolDataSource.MostuserswillprobablyfindinstantiatingComboPooledDataSourcetobethe mostconvenientapproach.Onceinstantiated,c3p0DataSourcescanbeboundtonearlyany JNDI-compliantnameservice. RegardlessofhowyoucreateyourDataSource,c3p0willusedefaultsforanyconfiguration parametersthatyoudonotspecifyprogrammatically.c3p0hasbuilt-in,hard-codeddefaults, butyoucanoverridethesebycreatingafilecalledc3p0.propertiesandstoringitasatop-level resourceinthesameCLASSPATH(orClassLoader)thatloadsc3p0'sjarfile.Asofc3p0-0.9.1, youcanalsosupplyafilecalledc3p0-config.xmlformoreadvancedconfiguration.See Configurationbelow.

InstantiatingandConfiguringaComboPooledDataSource
Perhapsthemoststraightforwardwaytocreateac3p0poolingDataSourceistoinstantiate aninstanceofcom.mchange.v2.c3p0.ComboPooledDataSource.ThisisaJavaBean-styleclasswitha public,no-argconstructor,butbeforeyouusetheDataSource,you'llhavetobesuretosetat leastthepropertyjdbcUrl.Youmayalsowanttosetuserandpassword,andifyouhavenot externallypreloadedtheold-styleJDBCdriveryou'lluseyoushouldsetthedriverClass.

ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" ); cpds.setUser("swaldman"); cpds.setPassword("test-password"); // the settings below are optional -- c3p0 can work with defaults cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); // The DataSource cpds is now a fully configured and usable pooled DataSource ...

4 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Thedefaultsofanyc3p0DataSourcearedeterminedbyconfigurationyousupply,orelse reverttohard-codeddefaults[seeconfigurationproperties].c3p0-0.9.1andabovesupports multiple,namedconfigurations.Ifyouwishtouseanamedconfiguration,constructyour com.mchange.v2.c3p0.ComboPooledDataSourcewiththeconfigurationnameasaconstructoragument:

ComboPooledDataSource cpds = new ComboPooledDataSource("intergalactoApp");

Ofcourse,youcanstilloverrideanyconfigurationpropertiesprogrammatically,asabove.

UsingtheDataSourcesfactoryclass
Alternatively,youcanusethestaticfactoryclasscom.mchange.v2.c3p0.DataSourcestobuild unpooledDataSourcesfromtraditionalJDBCdrivers,andtobuildpooledDataSourcesfrom unpooledDataSources:

DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password"); DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled ); // // // // ... The DataSource ds_pooled is now a fully configured and usable pooled DataSource. The DataSource is using a default pool configuration, and Postgres' JDBC driver is presumed to have already been loaded via the jdbc.drivers system property or an explicit call to Class.forName("org.postgresql.Driver") elsewhere.

IfyouusetheDataSourcesfactoryclass,andyouwanttoprogrammaticallyoverridedefault configurationparameters,youcansupplyamapofoverrideproperties:

DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password"); Map overrides = new HashMap(); overrides.put("maxStatements", "200"); //Stringified property values work overrides.put("maxPoolSize", new Integer(50)); //"boxed primitives" also work // create the PooledDataSource using the default configuration and our overrides ds_pooled = DataSources.pooledDataSource( ds_unpooled, overrides ); // The DataSource ds_pooled is now a fully configured and usable pooled DataSource, // with Statement caching enabled for a maximum of up to 200 statements and a maximum // of 50 Connections. ...

Ifyouareusingnamedconfigurations,youcanspecifytheconfigurationthatdefinesthe defaultconfigurationforyourDataSource:

5 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

// create the PooledDataSource using the a named configuration and specified overrides ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoAppConfig", overrides );

ShowdeprecatedPoolConfigapproach...
RARE:Forcingauthenticationinformation,regardlessof(mis)configurationoftheunderlying(unpooled) DataSource YoucanwrapanyDataSouceusingDataSource.pooledDataSource( ... ) ,usuallywithnoproblemwhatsoever. DataSourcesaresupposedtoindicatetheusernameandpasswordassociatedbydefaultwithConnectionsvia standardpropertiesuser andpassword .SomeDataSourceimplementationsdonotoffertheseproperties.Usually thisisnotatallaproblem.c3p0 worksaroundthisbyacquiring"default"ConnectionsfromtheDataSourceifit can'tfinddefaultauthenticationinformation,andaclienthasnotspecifiedtheauthentificationinformationvia getConnection( user, password ) . However,inrarecircumstances,non-c3p0unpooledDataSourcesprovideauser property,butnotapassword property,oryouhaveaccesstoaDataSourcethatyouwishtowrapbehindapool,butyouwishtooverrideits build-inauthentificationdefaultswithoutactuallymodifyingtheuser orpassword properties.
c3p0 providesconfiguationproperties overrideDefaultUser and overrideDefaultPassword .Ifyousetthese

properties,programmaticallyasabove,orviaanyofc3p0'sconfigurationmechanisms,c3p0 PooledDataSources willignoretheuserandpasswordpropertyassociatedwiththeunderlyingDataSource,andusethespecified overridesinstead.

QueryingaPooledDataSource'scurrentstatus
c3p0DataSourcesbackedbyapool,whichincludeimplementationsofComboPooledDataSource andtheobjectsreturnedbyDataSources.pooledDataSource( ... ),allimplementtheinterface com.mchange.v2.c3p0.PooledDataSource,whichmakesavailableanumberofmethodsforquerying thestatusofDataSourceConnectionpools.BelowissamplecodethatqueriesaDataSource foritsstatus:

// fetch a JNDI-bound DataSource InitialContext ictx = new InitialContext(); DataSource ds = (DataSource) ictx.lookup( "java:comp/env/jdbc/myDataSource" ); // make sure it's a c3p0 PooledDataSource if ( ds instanceof PooledDataSource) { PooledDataSource pds = (PooledDataSource) ds; System.err.println("num_connections: " + pds.getNumConnectionsDefaultUser()); System.err.println("num_busy_connections: " + pds.getNumBusyConnectionsDefaultUser()); System.err.println("num_idle_connections: " + pds.getNumIdleConnectionsDefaultUser()); System.err.println(); } else System.err.println("Not a c3p0 PooledDataSource!");

Thestatusqueryingmethodsallcomeinthreeoverloadedforms,suchas:

6 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

public int getNumConnectionsDefaultUser() public int getNumConnections(String username, String password) public int getNumConnectionsAllUsers()

c3p0maintainsseparatepoolsforConnectionswithdistinctauthentications.Thevarious methodsletyouquerythestatusofpoolsindividually,oraggregatestatisticsforall authentificationsforwhichyourDataSourceismaintainingpools.Notethatpoolconfiguration parmeterssuchasmaxPoolSizeareenforcedonaper-authentificationbasis!Forexample,if youhavesetmaxPoolSizeto20,andiftheDataSourceismanagingconnectionsundertwo username-passwordpairs[thedefault,andoneotherpairestablishedviaacallto getConnection(user, password),youshouldexpecttoseeasmanyas40Connectionsfrom getNumConnectionsAllUsers(). Mostapplicationsonlyacquiredefault-authenticatedConnectionsfromDataSources,and cantypicallyjustusethegetXXXDefaultUser()togatherConnectionstatistics. AswellasConnectionpoolrealtedstatistics,youcanretrievestatusinformationabouteach DataSource'sThreadpool.PleaseseePooledDataSourceforacompletelistofavailable operations.
UsingC3P0RegistrytogetareferencetoaDataSource Ifit'sinconvenientorimpossibletogetareferencetoyourDataSourceviaJNDIorsomeothermeans,youcan findalllivec3p0DataSourcesusingtheC3P0Registry class,whichincludesthreestaticmethodstohelpyouout:
public static Set getPooledDataSources() public static Set pooledDataSourcesByName( String dataSourceName ) public static PooledDataSource pooledDataSourceByName( String dataSourceName )

ThefirstmethodwillhandyoutheSetofalllivec3p0PooledDataSources.Ifyouaresureyourapplicationonly makesonePooledDataSources,oryoucandistinguishbetweentheDataSourcesbytheirconfigurationproperties (inspectedvia"getters"),thefirstmethodmaybesufficient.Becausethiswillnotalwaysbethecase,c3p0 PooledDataSourceshaveaspecialpropertycalleddataSourceName .YoucansetthedataSourceName property directlywhenyouconstructyourDataSource,ordataSourceNamecanbesetlikeanyotherpropertyinanamedor thedefaultconfig.Otherwise,dataSourceName willdefaulttoeither1)thenameofyourDataSource's configuration,ifyouconstructeditwithanamedconfiguration;or2)aunique(butunpredicatble)nameifyouare usingthedefaultconfiguration. ThereisnoguaranteethatadataSourceName willbeunique.Forexample,iftwoc3p0DataSourcessharethe samenamedconfiguration,andyouhavenotsetthedataSourceName programmatically,thetwodatasourceswill bothsharethenameoftheconfiguration.TogetalloftheDataSourceswithaparticulardataSourceName ,use pooledDataSourcesByName( ... ) .Ifyou'veensuredthatyourDataSource'snameisunique(asyouwillgenerally wanttodo,ifyouintendtouseC3P0Registry tofindyourDataSources),youcanusetheconveniencemethod pooledDataSourceByName( ... ) ,whichwillreturnyourDataSourcedirectly,or null ifnoDataSourcewiththat nameisavailable.IfyouusepooledDataSourceByName( ... ) andmorethanoneDataSourcesharesthename supplied,whichoneitwillreturnisundefined.

Cleaningupafterc3p0PooledDataSources
Theeasywaytocleanupafterc3p0-createdDataSourcesistousethestaticdestroymethod definedbytheclassDataSources.OnlyPooledDataSourcesneedtobecleanedup,but
7 de 34 23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

DataSources.destroy(...)doesnoharmifitiscalledonanunpooledornon-c3p0 DataSource.

DataSource ds_pooled

= null;

try { DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password"); ds_pooled = DataSources.pooledDataSource( ds_unpooled ); // do all kinds of stuff with that sweet pooled DataSource... } finally { DataSources.destroy( ds_pooled ); }

Alternatively,c3p0'sPooledDataSourceinterfacecontainsaclose()methodthatyoucancall whenyouknowyouarefinishedwithaDataSource.So,youcancastac3p0derived DataSourcetoaPooledDataSourceandcloseit:

static void cleanup(DataSource ds) throws SQLException { // make sure it's a c3p0 PooledDataSource if ( ds instanceof PooledDataSource) { PooledDataSource pds = (PooledDataSource) ds; pds.close(); } else System.err.println("Not a c3p0 PooledDataSource!"); }

UnreferencedinstancesofPooledDataSourcethatarenotclose()edbyclientsclose()themselves priortogarbagecollectionintheirfinalize()methods.Asalways,finalizationshouldbe consideredabackstopandnotapromptorsureapproachtoresourcecleanup.

Advanced:BuildingyourownPoolBackedDataSource
Thereislittlereasonformostprogrammerstodothis,butyoucanbuildaPooledDataSource inastep-by-stepwaybyinstantiatingandconfiguringanunpooledDriverManagerDataSource, instantiatingaWrapperConnectionPoolDataSourceandsettingtheunpooledDataSourceasits nestedDataSourceproperty,andthenusingthattosettheconnectionPoolDataSourcepropertyofa newPoolBackedDataSource. Thissequenceofeventsisprimarilyinterestingifyourdriveroffersanimplementationof ConnectionPoolDataSource,andyou'dlikec3p0tousethat.Ratherthanusingc3p0's WrapperConnectionPoolDataSource,youcancreateaPoolBackedDataSourceandsetits connectionPoolDataSourceproperty.Statementpooling,ConnectionCustomizers,andmany c3p0-specificpropertiesareunsupportedwiththirdpartyimplementationsof
8 de 34 23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

ConnectionPoolDataSource.(Third-partyDataSourceimplementationscanbesubstitutedforc3p0's DriverManagerDataSourcewithnosignificantlossoffunctionality.)

Advanced:RawConnectionandStatementOperations
JDBCdriverssometimesdefinevendor-specific,non-standardAPIonConnectionand Statementimplementations.C3P0wrapstheseObjectsbehindaproxies,soyoucannotcast C3P0-returnedConnectionsorStatementstothevendor-specificimplementationclasses. C3P0doesnotprovideanymeansofaccessingtherawConnectionsandStatements directly,becauseC3P0needstokeeptrackofStatementsandResultSetscreatedinorderto preventresourceleaksandpoolcorruption. C3P0doesprovideanAPIthatallowsyoutoinvokenon-standardmethodsreflectivelyonan underlyingConnection.Touseit,firstcastthereturnedConnectiontoaC3P0ProxyConnection. ThencallthemethodrawConnectionOperation,supplyingthejava.lang.reflect.Methodobjectforthe non-standardmethodyouwishtocallasanargument.TheMethodyousupplywillbeinvoked onthetargetyouprovideonthesecondargument(nullforstaticmethods),andusingthe argumentsyousupplyinthethirdargumenttothatfunction.Forthetarget,andforanyofthe methodarguments,youcansupplythespecialtokenC3P0ProxyConnection.RAW_CONNECTION,which willbereplacedwiththeunderlyingvendor-specificConnectionobjectbeforetheMethodis invoked.
C3P0ProxyStatementoffersanexactlyanalogousAPI.

AnyStatements(includingPreparedandCallableStatements)andResultSetsreturnedby rawoperationswillbec3p0-managed,andwillbeproperlycleaned-uponclose()ofthe parentproxyConnection.Usersmusttakecaretocleanupanynon-standardresources returnedbyavendor-specificmethod. Here'sanexampleofusingOracle-specificAPItocallastaticmethodonarawConnection:

C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection(); Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class}); Object[] args = new Object[] {C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )}; CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args);

Note:C3P0nowincludesspecialsupportforsomeOracle-specificmethods.SeeAppendixF.

Configuration
Introduction
Whilec3p0doesnotrequireverymuchconfiguration,itisverytweakable.Mostofthe interestingknobsanddialsarerepresentedasJavaBeanproperties.FollowingJavaBean

9 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

conventions,wenotethatifanObjecthasapropertyoftypeTcalledfoo,itwillhavemethods thatlooklike...
public T getFoo(); public void setFoo(T foo);

...orboth,dependinguponwhetherthepropertyisread-only,write-only,orread-writable. Thereareseveralwaystomodifyc3p0properties:Youcandirectlyalterthepropertyvalues associatedwithaparticularDataSourceinyourcode,oryoucanconfigurec3p0externally, viaasimpleJavapropertiesfile,viaanXMLconfigurationfile,orviaSystemproperties. DataSourcesareusuallyconfiguredbeforetheyareused,eitherduringorimmediately followingtheirconstruction.c3p0doessupportpropertymodificationsmidstream,however. IfyouobtainaDataSourcebyinstantiatingaComboPooledDataSource,configureitbysimply callingappropriatesettermethodsofferedbythatclassbeforeattemptingacallto getConnection().Seetheexampleabove. IfyouobtainaDataSourcebyusingfactorymethodsoftheutilityclass com.mchange.v2.c3p0.DataSources,andwishtouseanon-defaultconfiguration,youcansupplya Mapofpropertynames(beginningwithlower-caseletters)topropertyvalues(eitheras Stringsor"boxed"JavaprimitiveslikeIntegerorBoolean). AlltweakablepropertiesaredocumentedforreferenceinAppendixA.Themostbasicand importantc3p0configurationtopicsarediscussedbelow.

BasicPoolConfiguration
c3p0Connectionpoolsareveryeasytoconfigureviathefollowingbasicparameters:
acquireIncrement initialPoolSize maxPoolSize maxIdleTime minPoolSize initialPoolSize,minPoolSize,maxPoolSizedefinethenumberofConnectionsthatwillbepooled.

PleaseensurethatminPoolSize <= maxPoolSize.UnreasonablevaluesofinitialPoolSizewillbe ignored,andminPoolSizewillbeusedinstead. WithintherangebetweenminPoolSizeandmaxPoolSize,thenumberofConnectionsinapool variesaccordingtousagepatterns.ThenumberofConnectionsincreaseswhenevera Connectionisrequestedbyauser,noConnectionsareavailable,andthepoolhasnotyet reachedmaxPoolSizeinthenumberofConnectionsmanaged.SinceConnectionacquisitionis veryslow,itisalmostalwaysusefultoincreasethenumberofConnectionseagerly,in batches,ratherthanforcingeachclienttowaitforanewConnectiontoprovokeasingle acquisitionwhentheloadisincreasing.acquireIncrementdetermineshowmanyConnectionsa c3p0poolwillattempttoacquirewhenthepoolhasrunoutofConnections.(Regardlessof

10 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

acquireIncrement,thepoolwillneverallowmaxPoolSizetobeexceeded.)

ThenumberofConnectionsinapooldecreaseswheneverapooltestsaConnectionand findsittobebroken(seeConfiguringConnectionTestingbelow),orwhenaConnectionis expiredbythepoolaftersittingidleforaperiodoftime,orforbeingtooold(SeeManaging PoolSizeandConnectionAge.)

ManagingPoolSizeandConnectionAge
Differentapplicationshavedifferentneedswithregardtotrade-offsbetweenperformance, footprint,andreliability.C3P0offersawidevarietyofoptionsforcontrollinghowquicklypools thathavegrownlargeunderloadreverttominPoolSize,andwhether"old"Connectionsinthe poolshouldbeproactivelyreplacedtomaintaintheirreliablity.
maxConnectionAge maxIdleTime maxIdleTimeExcessConnections

Bydefault,poolswillneverexpireConnections.IfyouwishConnectionstobeexpiredover timeinordertomaintain"freshness",setmaxIdleTimeand/ormaxConnectionAge.maxIdleTimedefines howmanysecondsaConnectionshouldbepermittedtogounusedbeforebeingculledfrom thepool.maxConnectionAgeforcesthepooltocullanyConnectionsthatwereacquiredfromthe databasemorethanthesetnumberofsecondsinthepast.


maxIdleTimeExcessConnectionsisaboutminimizingthenumberofConnectionsheldbyc3p0pools

whenthepoolisnotunderload.Bydefault,c3p0poolsgrowunderload,butonlyshrinkif ConnectionsfailaConnectiontestorareexpiredawayviatheparametersdescribedabove. SomeuserswanttheirpoolstoquicklyreleaseunnecessaryConnectionsafteraspikein usagethatforcesalargepoolsize.YoucanachievethisbysettingmaxIdleTimeExcessConnections toavaluemuchshorterthanmaxIdleTime,forcingConnectionsbeyondyoursetminimumsize tobereleasediftheysitidleformorethanashortperiodoftime. Somegeneraladviceaboutallofthesetimeoutparameters:Slowdown!Thepointof ConnectionpoolingistobearthecostofacquiringaConnectiononlyonce,andthentoreuse theConnectionmany,manytimes.MostdatabasessupportConnectionsthatremainopenfor hoursatatime.There'snoneedtochurnthroughallyourConnectionseveryfewsecondsor minutes.SettingmaxConnectionAgeormaxIdleTimeto1800(30minutes)isquiteaggressive.For mostdatabases,severalhoursmaybemoreappropriate.Youcanensurethereliabilityof yourConnectionsbytestingthem,ratherthanbytossingthem.(seeConfiguringConnection Testing.)Theonlyoneoftheseparametersthatshouldgenerallybesettoafewminutesor lessismaxIdleTimeExcessConnections.

ConfiguringConnectionTesting
c3p0canbeconfiguredtotesttheConnectionsthatitpoolsinavarietyofways,tominimize thelikelihoodthatyourapplicationwillseebrokenor"stale"Connections.Pooled Connectionscangobadforavarietyofreasons--someJDBCdriversintentionally"time-out"

11 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

long-lastingdatabaseConnections;back-enddatabasesornetworkssometimesgodown "stranding"pooledConnections;andConnectionscansimplybecomecorruptedovertime anduseduetoresourceleaks,driverbugs,orothercauses. c3p0providesusersagreatdealofflexibilityintestingConnections,viathefollowing configurationparameters:


automaticTestTable connectionTesterClassName idleConnectionTestPeriod preferredTestQuery testConnectionOnCheckin testConnectionOnCheckout idleConnectionTestPeriod,testConnectionOnCheckout,andtestConnectionOnCheckincontrolwhen

Connectionswillbetested.automaticTestTable,connectionTesterClassName,andpreferredTestQuery controlhowtheywillbetested. WhenconfiguringConnectiontesting,firsttrytominimizethecostofeachtest.Bydefault, ConnectionsaretestedbycallingthegetTables()methodonaConnection'sassociated DatabaseMetaDataobject.Thishastheadvantageofworkingwithanydatabase,andregardless ofthedatabaseschema.However,empiricallyaDatabaseMetaData.getTables()callisoftenmuch slowerthanasimpledatabasequery. ThemostconvenientwaytospeedupConnectiontestingistodefinetheparameter


automaticTestTable.Usingthenameyouprovide,c3p0willcreateanemptytable,andmakea

simplequeryagainstittotestthedatabase.Alternatively,ifyourdatabaseschemaisfixed priortoyourapplication'suseofthedatabase,youcansimplydefineatestquerywiththe preferredTestQueryparameter.Becareful,however.SettingpreferredTestQuerywillleadtoerrors asConnectiontestsfailifthequerytargettabledoesnotexistinyourdatabasetablepriorto initializationofyourDataSource. AdvancedusersmaydefineanykindofConnectiontestingtheywish,byimplementinga ConnectionTesterandsupplyingthefullyqualifiednameoftheclassas connectionTesterClassName.Ifyou'dlikeyourcustomConnectionTesterstohonorandsupportthe preferredTestQueryandautomaticTestTableparameters,implementUnifiedConnectionTester, mostconvenientlybyextendingAbstractConnectionTester.Seetheapidocsformore information. ThemostreliabletimetotestConnectionsisoncheck-out.Butthisisalsothemostcostly choicefromaclient-performanceperspective.Mostapplicationsshouldworkquitereliably usingacombinationofidleConnectionTestPeriodandtestConnectionsOnCheckIn.Boththeidletest andthecheck-intestareperformedasynchronously,whichleadstobetterperformance,both perceivedandactual. Notethatformanyapplications,highperformanceismoreimportantthantheriskofan occasionaldatabaseexception.Initsdefaultconfiguration,c3p0doesnoConnectiontesting atall.SettingafairlylongidleConnectionTestPeriod,andnottestingoncheckoutandcheck-inat

12 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

allisanexcellent,high-performanceapproach.

ConfiguringStatementPooling
c3p0implementstransparentPreparedStatementpoolingasdefinedbytheJDBCspec. Undersomecircumstances,statementpoolingcandramaticallyimproveapplication performance.Underothercircumstances,theoverheadofstatementpoolingcanslightly harmperformance.Whetherandhowmuchstatementpoolingwillhelpdependsonhow muchparsing,planning,andoptimizingofqueriesyourdatabasesdoeswhenthestatements areprepared.Databases(andJDBCdrivers)varywidelyinthisrespect.It'sagoodideato benchmarkyourapplicationwithandwithoutstatementpoolingtoseeifandhowmuchit helps. Youconfigurestatementpoolinginc3p0viathefollowingconfigurationparameters:
maxStatements maxStatementsPerConnection maxStatementsisJDBC'sstandardparameterforcontrollingstatementpooling.maxStatements

definesthetotalnumberPreparedStatementsaDataSourcewillcache.Thepoolwilldestroythe least-recently-usedPreparedStatementwhenithitsthislimit.Thissoundssimple,butit's actuallyastrangeapproach,becausecachedstatementsconceptuallybelongtoindividual Connections;theyarenotglobalresources.TofigureoutasizeformaxStatementsthatdoesnot "churn"cachedstatements,youneedtoconsiderthenumberoffrequentlyused PreparedStatementsinyourapplication,andmultiplythatbythenumberofConnectionsyou expectinthepool(maxPoolSizeinabusyapplication).


maxStatementsPerConnectionisanon-standardconfigurationparameterthatmakesabitmore

senseconceptually.ItdefineshowmanystatementseachpooledConnectionisallowedto own.YoucansetthistoabitmorethanthenumberofPreparedStatementsyourapplication frequentlyuses,toavoidchurning. Ifeitheroftheseparametersaregreaterthanzero,statementpoolingwillbeenabled.Ifboth parametersaregreaterthanzero,bothlimitswillbeenforced.Ifonlyoneisgreaterthanzero, statementpoolingwillbeenabled,butonlyonelimitwillbeenforced.

ConfiguringRecoveryFromDatabaseOutages
c3p0DataSourcesaredesigned(andconfiguredbydefault)torecoverfromtemporary databaseoutages,suchasthosewhichoccurduringadatabaserestartorbrieflossof networkconnectivity.Youcanaffecthowc3p0handleserrorsinacquiringConnectionsvia thefollowingconfigurableproperties:
acquireRetryAttempts acquireRetryDelay breakAfterAcquireFailure

Whenac3p0DataSourceattemptsandfailstoacquireaConnection,itwillretryupto

13 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

acquireRetryAttemptstimes,withadelayofacquireRetryDelaybetweeneachattempt.Ifallattempts

fail,anyclientswaitingforConnectionsfromtheDataSourcewillseeanException,indicating thataConnectioncouldnotbeacquired.NotethatclientsdonotseeanyExceptionuntilafull roundofattemptsfail,whichmaybesometimeaftertheinitialConnectionattempt.If acquireRetryAttemptsissetto0,c3p0willattempttoacquirenewConnectionsindefinitely,and callstogetConnection()mayblockindefinitelywaitingforasuccessfulacquisition. Onceafullroundofacquisitionattemptsfails,therearetwopossiblepolicies.Bydefault,the c3p0DataSourcewillremainactive,andwilltryagaintoacquireConnectionsinresponseto futurerequestsforConnections.IfyousetbreakAfterAcquireFailuretotrue,theDataSourcewill consideritselfbrokenafterafailedroundofConnectionattempts,andfutureclientrequests willfailimmediately. Notethatifadatabaserestartoccurs,apoolmaycontainpreviouslyacquiredbutnowstale Connections.Bydefault,thesestaleConnectionswillonlybedetectedandpurgedlazily, whenanapplicationattemptstousethem,andseesanException.SettingmaxIdleTimeor maxConnectionAgecanhelpspeedupthereplacementofbrokenConnections.(SeeManaging ConnectionAge.)IfyouwishtoavoidapplicationExceptionsentirely,youmustadopta connectiontestingstrategythatislikelytodetectstaleConnectionspriortotheirdeliveryto clients.(See"ConfiguringConnectionTesting".)EvenwithactiveConnectiontesting (testConnectionsOnCheckoutsettotrue,ortestConnectionsOnCheckinandashort idleConnectionTestPeriod),yourapplicationmayseeoccasionalExceptionsondatabaserestart, forexampleiftherestartoccursafteraConnectiontothedatabasehasalreadybeen checkedout.

ManagingConnectionLifecycleswithConnectionCustomizer
ApplicationfrequentlywishtosetupConnectionsinsomestandard,reusableway immediatelyafterConnectionacquisitions.Examplesofthisincludesetting-upcharacter encodings,ordateandtimerelatedbehavior,usingvendor-specificAPIsornon-standard SQLstatementexecutions.Occasionallyitisusefultooverridethedefaultvaluesofstandard ConnectionpropertiessuchastransactionIsolation,holdability,orreadOnly.c3p0providesa "hook"interfacethatyoucanimplement,whichgivesyoutheopportunitytomodifyortrack Connectionsjustaftertheyarecheckedoutfromthedatabase,immediatelyjustpriortobeing handedtoclientsoncheckout,justpriortobeingreturnedtothepooloncheck-in,andjust priortofinaldestructionbythepool.TheConnectionshandedtoConnectionCustomizersare raw,physicalConnections,withallvendor-specificAPIaccessible.SeetheAPIdocsfor ConnectionCustomizer. ToinstallaConnectionCustomizerjustimplementtheinterface,makeyourclassaccessibleto c3p0'sClassLoader,andsettheconfigurationparameterbelow:
connectionCustomizerClassName

ConnectionCustomizersarerequiredtobeimmutableclasseswithpublicnoargument constructors.Theyshouldn'tstoreanystate.For(rare)applicationsthatwishtotrackthe behaviorofindividualDataSourceswithConnectionCustomizers,thelifecyclemethodseach

14 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

acceptaDataSource-specific"identityToken",whichisuniquetoeachPooledDataSource. BelowisasampleConnectionCustomizer.Implementationsthatdonotneedtooverrideallfour ConnectionCustomizermethodscanextendAbstractConnectionCustomizertoinheritno-op implementationsofallmethods.

import com.mchange.v2.c3p0.*; import java.sql.Connection; public class VerboseConnectionCustomizer { public void onAcquire( Connection c, String pdsIdt ) { System.err.println("Acquired " + c + " [" + pdsIdt + "]"); // override the default transaction isolation of // newly acquired Connections c.setTransactionIsolation( Connection.REPEATABLE_READ ); } public void onDestroy( Connection c, String pdsIdt ) { System.err.println("Destroying " + c + " [" + pdsIdt + "]"); } public void onCheckOut( Connection c, String pdsIdt ) { System.err.println("Checked out " + c + " [" + pdsIdt + "]"); } public void onCheckIn( Connection c, String pdsIdt ) { System.err.println("Checking in " + c + " [" + pdsIdt + "]"); } }

ConfiguringUnresolvedTransactionHandling
Connectionscheckedintoapoolcannothaveanyunresolvedtransactionalworkassociated withthem.IfusershavesetautoCommittofalseonaConnection,andc3p0cannotguarantee thatthereisnopendingtransactionalwork,c3p0musteitherrollback()orcommit()oncheck-in (whenausercallsclose()).TheJDBCspecis(unforgivably)silentonthequestionofwhether unresolvedworkshouldbecommittedorrolledbackonConnectionclose.Bydefault,c3p0 rollsbackunresolvedtransactionalworkwhenausercallsclose(). Youcanadjustthisbehaviorviathefollowingconfigurationproperties:
autoCommitOnClose forceIgnoreUnresolvedTransactions

Ifyouwishc3p0toallowunresolvedtransactionalworktocommitoncheckin,set autoCommitOnClosetotrue.Ifyouwishc3p0toleavetransactionmanagementtoyou,andneither commitnorrollback(normodifythestateofConnectionautoCommit),youmayset forceIgnoreUnresolvedTransactionstotrue.SettingforceIgnoreUnresolvedTransactionsisstrongly discouraged,becauseifclientsarenotcarefultocommitorrollbackthemselvespriorto close(),ordonotsetConnectionautoCommitconsistently,bizarreunreproduceablebehavior anddatabaselockupscanoccur.

ConfiguringtoDebugandWorkaroundBrokenClientApplications

15 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Sometimesclientapplicationsaresloppyaboutclose()ingallConnectionstheycheckout. Eventually,thepoolgrowstomaxPoolSize,andthenrunsoutofConnections,becauseofthese badclients. Therightwaytoaddressthisproblemistofixtheclientapplication.c3p0canhelpyoudebug, bylettingyouknowwhereConnectionsarecheckedoutthatoccasionallydon'tgetchecked in.Inrareandunfortunatesituations,developmentoftheclientapplicationisclosed,and eventhoughitisbuggy,youcannotfixit.c3p0canhelpyouworkaroundthebroken application,preventingitfromexhaustingthepool. Thefollowingparameterscanhelpyoudebugorworkaroundbrokenclientapplications.


debugUnreturnedConnectionStackTraces unreturnedConnectionTimeout unreturnedConnectionTimeoutdefinesalimit(inseconds)tohowlongaConnectionmayremain

checkedout.Ifsettoanozerovalue,unreturned,checked-outConnectionsthatexceedthis limitwillbesummarilydestroyed,andthenreplacedinthepool.Obviously,youmusttake caretosetthisparametertoavaluelargeenoughthatallintendedoperationsonchecked outConnectionshavetimetocomplete.Youcanusethisparametertomerelyworkaround unreliableclientappsthatfailtoclose()Connections. Muchbetterthanworking-aroundisfixing.If,inadditiontosettingunreturnedConnectionTimeout, yousetdebugUnreturnedConnectionStackTracestotrue,thenastacktracewillbecapturedeachtime aConnectionischecked-out.WheneveranunreturnedConnectiontimesout,thatstacktrace willbeprinted,revealingwhereaConnectionwascheckedoutthatwasnotcheckedin promptly.debugUnreturnedConnectionStackTracesisintendedtobeusedonlyfordebugging,as capturingastacktracecanslowdownConnectioncheck-out.

OtherDataSourceConfiguration
SeeAppendixAforinformationaboutthefollowingconfigurationproperties:
checkoutTimeout factoryClassLocation maxAdministrativeTaskTime numHelperThreads usesTraditionalReflectiveProxies numHelperThreadsandmaxAdministrativeTaskTimehelptoconfigurethebehaviorofDataSource

threadpools.Bydefault,eachDataSourcehasonlythreeassociatedhelperthreads.If performanceseemstodragunderheavyload,orifyouobserveviaJMXordirectinspection ofaPooledDataSource,thatthenumberof"pendingtasks"isusuallygreaterthanzero,try increasingnumHelperThreads.maxAdministrativeTaskTimemaybeusefulforusersexperiencingtasks thathangindefinitelyand"APPARENTDEADLOCK"messages.(SeeAppendixAformore.)


checkoutTimeoutlimitshowlongaclientwillwaitforaConnection,ifallConnectionsare

checkedoutandonecannotbesuppliedimmediately.usesTraditionalReflectiveProxies,which

16 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

isoflittlepracticaluse,permitsyoutouseanold,nowsupercededimplementationof C3P0-generatedproxyobjects.(C3P0usedtousereflective,dynamicproxies.Now,for enhancedperformance,itusescode-generated,nonrefectiveimplementations.) factoryClassLocationcanbeusedtoindicatewhereaURLfromwhichc3p0classescanbe downloaded,ifc3p0DataSourceswillberetrievedasReferencesfromaJNDIDataSource byclientswhodonothavec3p0locallyinstalled.

ConfiguringandManagingc3p0viaJMX
IfJMXlibrariesandaJMXMBeanServerareavailableinyourenvironment(theyareinclude inJDK1.5andabove),youcaninspectandconfigureyourc3p0datasourcesviaaJMX administrationtool(suchasjconsole,bundledwithjdk1.5).Youwillfindthatc3p0registers MBeansundercom.mchange.v2.c3p0,onewithstatisticsaboutthelibraryasawhole(called C3P0Registry),andanMBeanforeachPooledDataSourceyoudeploy.Youcanviewandmodify yourDataSource'sconfigurationproperties,tracktheactivityofConnection,Statement,and Threadpools,andresetpoolsandDataSourcesviathePooledDataSourceMBean.(Youmay wishtoviewtheAPIdocsofPooledDataSourcefordocumentationoftheavailableoperations.) Ifyoudonotwantc3p0toregisterMBeanswithyourJMXenvironment,youcansuppressthis behaviorwiththefollowing,seteitherasaSystempropertyorinc3p0.properties:

com.mchange.v2.c3p0.management.ManagementCoordinator=com.mchange.v2.c3p0.management.NullManagementCoordinator

ConfiguringLogging
c3p0usesacustomlogginglibrarysimilartojakartacommons-logging.Logmessagescan bedirectedtothepopularlog4jlogginglibrary,tothestandardloggingfacilityintroducedwith jdk1.4,ortoSystem.err.Nearlyallconfigurationshouldbedoneatthelevelofyourpreferred logginglibrary.Thereareaveryfewconfigurationoptionsspecifictoc3p0'slogging,and usuallythedefaultswillbefine.Logging-relatedparametersmaybeplacedinyour c3p0.propertiesfile,inafilecalledmchange-log.propertiesatthetop-levelofyourclasspath,or theymaybedefinedasSystemproperties.(Theloggingpropertiesdefinedbelowmaynotbe definedinc3p0-config.xml!)Seetheboxbelow. c3p0'sloggingbehaviorisaffectedbycertainbuild-timeoptions.Ifbuild-optionc3p0.debugis settofalse,allmessagesatalogginglevelbelowINFOwillbesuppressed.Build-option c3p0.tracecontrolshowfine-grainedc3p0'sbelowINFOlevelreportingwillbe.Forthe moment,distributedc3p0binariesarecompiledwithdebugsettotrueandtracesettoits maximumlevelof10.Butbinariesmayeventuallybedistributedwithdebugsettofalse.(Forthe moment,theperformanceimpactofthelogginglevel-checksseemsverysmall,andit'smost flexibletocompileinallthemessages,andletyourlogginglibrarycontrolwhichareemitted.) Whenc3p0startsup,itemitsthebuild-timevaluesofdebugandtrace,alongwiththeversion andbuildtime.

17 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

com.mchange.v2.log.MLog

Determineswhichlibraryc3p0willoutputlogmessagesto.Bydefault,iflog4jisavailable,itwillusethat library,otherwiseifjdk1.4loggingapisareavailableitwillusethose,andifneitherareavailable,itwillusea simplefallbackthatlogstoSystem.err .Ifyouwanttodirectlycontrolwhichlibraryisused,youmaysetthis propertytooneof:


com.mchange.v2.log.log4j.Log4jMLog com.mchange.v2.log.jdk14logging.Jdk14MLog com.mchange.v2.log.FallbackMLog

Youmayalsosetthispropertytoacommaseparatedlistoftheabovealternatives,todefineanorderof preferenceamonglogginglibraries.
com.mchange.v2.log.NameTransformer

Bydefault,c3p0usesveryfine-grainedlogging,ingeneralwithoneloggerforeachc3p0class.Foravarietyof reasons,someusersmaypreferfewer,moregloballoggers.Youmayoptforone-logger-per-packageby settingcom.mchange.v2.log.NameTransformer tothevaluecom.mchange.v2.log.PackageNames .Advanced userscanalsodefineotherstrategiesfororganizingthenumberandnamesofloggersbysettingthisvariable tothefully-qualifiedclassnameofacustomimplementationofthecom.mchange.v2.log.NameTransformer interface.


com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL

If,whetherbychoiceorbynecessity,youareusingc3p0'sSystem.err fallbacklogger,youcanusethis parametertocontrolhowdetailedc3p0'sloggingshouldbe.Anyofthefollowingvalues(takenfromthejdk1.4 logginglibrary)areacceptable:


OFF SEVERE WARNING INFO CONFIG FINE FINER FINEST ALL

ThispropertydefaultstoINFO .

Performance
EnhancedperformanceisthepurposeofConnectionandStatementpooling,andamajor goalofthec3p0library.Formostapplications,Connectionpoolingwillprovideasignificant performancegain,especiallyifyouareacquiringanunpooledConnectionforeachclient access.Ifyouarelettingasingle,sharedConnectionservemanyclientstoavoidConnection acquisitionoverhead,youmaysufferperformanceissuesandproblemsmanaging transactionswhenyourConnectionisunderconcurrentload;Connectionpoolingwillenable youtoswitchtoaoneConnection-per-clientmodelwithlittleornocost.Ifyouarewriting EnterpriseJavaBeans,youmaybetemptedtoacquireaConnectiononceandnotreturnit untilthebeanisabouttobedestroyedorpassivated.Butthiscanberesource-costly,as dormantpooledbeansneedlesslyholdtheConnection'snetworkanddatabaseresources. Connectionpoolingpermitsbeanstoonly"own"aConnectionwhiletheyareusingit. But,thereareperformancecoststoc3p0aswell.Inordertoimplementautomaticcleanupof

18 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

unclosedResultSetsandStatementswhenparentresourcesarereturnedtopools,allclientvisibleConnections,ResultSets,Statementsarereallywrappersaroundobjectsprovidedbyan underlyingunpooledDataSourceor"traditional"JDBCdriver.Thus,thereissomeextra overheadtoallJDBCcalls. Someattentionhasbeenpaidtominimizingthe"wrapper"overheadofc3p0.Inmy environment,thewrapperoverheadamountsfromseveralhundrethstoseveralthousandths ofthecostofConnectionacquisition,sounlessyouaremakingmany,manyJDBCcallsin fastsuccession,therewillbeanetgaininperformanceandresource-utilizationefficiency. Significantly,theoverheadassociatedwithResultSetoperations(whereonemightiterate throughatablewiththousandsofrecords)appearstobenegligiblysmall.

KnownShortcomings
ConnectionsandStatementsarepooledonaper-authenticationbasis.So,ifone pool-backedDataSourceisusedtoacquireConnectionsbothfor[user=alice, password=secret1]and[user=bob,password=secret2],therewillbetwodistinctpools,and theDataSourcemightintheworstcasemanagetwicethenumberofConnections specifiedbythemaxPoolSizeproperty. ThisfactisanaturalconsequenceofthedefinitionoftheDataSourcespec(which allowsConnectionstobeacquiredwithmultipleuserauthentications),andthe requirementthatallConnectionsinasinglepoolbefunctionallyidentical.This"issue" willnotbechangedorfixed.It'snotedherejustsoyouunderstandwhat'sgoingon. TheoverheadofStatementpoolingistoohigh.Fordriversthatdonotperform significantpreprocessingofPreparedStatements,thepoolingoverheadoutweighsany savings.Statementpoolingisthusturnedoffbydefault.Ifyourdriverdoespreprocess PreparedStatements,especiallyifitdoessoviaIPCwiththeRDBMS,youwillprobablysee asignificantperformancegainbyturningStatementpoolingon.(Dothisbysettingthe configurationpropertymaxStatementsormaxStatementsPerConnectiontoavaluegreaterthan zero.).

FeedbackandSupport
Pleaseprovideanyandallfeedbackto<swaldman@mchange.com>!Also,feelfreetojoin andaskquestionsonthec3p0-usersmailinglist.Signupathttp://sourceforge.net/projects /c3p0/ Thankyouforusingc3p0!!!

AppendixA:ConfigurationProperties
19 de 34 23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

c3p0configurationpropertiescanbedividedintoJavaBeans-stylePropertiesandOther Properties.

JavaBeans-styleProperties
ThefollowingpropertiescanbesetdirectlyincodeasJavaBeansproperties,viaaSystem propertiesorac3p0.propertiesfile(withc3p0.prependedtothepropertyname),orina c3p0-config.xmlfile.SeethesectiononConfigurationabove.Clickonthepropertynamefora fulldescription.
acquireIncrement acquireRetryAttempts acquireRetryDelay autoCommitOnClose automaticTestTable breakAfterAcquireFailure checkoutTimeout connectionCustomizerClassName connectionTesterClassName debugUnreturnedConnectionStackTraces factoryClassLocation forceIgnoreUnresolvedTransactions idleConnectionTestPeriod initialPoolSize maxAdministrativeTaskTime maxConnectionAge maxIdleTime maxIdleTimeExcessConnections maxPoolSize maxStatements maxStatementsPerConnection minPoolSize numHelperThreads overrideDefaultUser overrideDefaultPassword password preferredTestQuery propertyCycle testConnectionOnCheckin testConnectionOnCheckout unreturnedConnectionTimeout user usesTraditionalReflectiveProxies

acquireIncrement

Default:3 Determineshowmanyconnectionsatatimec3p0willtrytoacquirewhenthepoolis exhausted.[See"BasicPoolConfiguration"]


acquireRetryAttempts

Default:30 Defineshowmanytimesc3p0willtrytoacquireanewConnectionfromthedatabasebefore givingup.Ifthisvalueislessthanorequaltozero,c3p0willkeeptryingtofetchaConnection indefinitely.[See"ConfiguringRecoveryFromDatabaseOutages"]


acquireRetryDelay

Default:1000 Milliseconds,timec3p0willwaitbetweenacquireattempts.[See"ConfiguringRecoveryFrom DatabaseOutages"]


autoCommitOnClose

Default:false TheJDBCspecisunforgivablysilentonwhatshouldhappentounresolved,pending transactionsonConnectionclose.C3P0'sdefaultpolicyistorollbackanyuncommitted,pending work.(Ithinkthisisabsolutely,undeniablytherightpolicy,butthereisnoconsensusamong JDBCdrivervendors.)SettingautoCommitOnClose totruecausesuncommittedpendingwork tobecommitted,ratherthanrolledbackonConnectionclose.[Note:Sincethespecisabsurdly unclearonthisquestion,applicationauthorswhowishtoavoidbugsandinconsistentbehavior shouldensurethatalltransactionsareexplicitlyeithercommittedorrolled-backbeforecloseis called.][See"ConfiguringUnresolvedTransactionHandling"]

20 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

automaticTestTable

Default:null Ifprovided,c3p0willcreateanemptytableofthespecifiedname,andusequeriesagainstthat tabletotesttheConnection.IfautomaticTestTable isprovided,c3p0willgenerateitsowntest query,thereforeanypreferredTestQuery setwillbeignored.Youshouldnotworkwiththe namedtableafterc3p0createsit;itshouldbestrictlyforc3p0'suseintestingyourConnection. (IfyoudefineyourownConnectionTester,itmustimplementtheQueryConnectionTester interfaceforthisparametertobeuseful.)[See"ConfiguringConnectionTesting"]


breakAfterAcquireFailure

Default:false Iftrue,apooledDataSourcewilldeclareitselfbrokenandbepermanentlyclosedifaConnection cannotbeobtainedfromthedatabaseaftermakingacquireRetryAttempts toacquireone.If false,failuretoobtainaConnectionwillcauseallThreadswaitingforthepooltoacquirea ConnectiontothrowanException,buttheDataSourcewillremainvalid,andwillattemptto acquireagainfollowingacalltogetConnection() .[See"ConfiguringRecoveryFromDatabase Outages"]


checkoutTimeout

Default:0 ThenumberofmillisecondsaclientcallinggetConnection()willwaitforaConnectiontobe checked-inoracquiredwhenthepoolisexhausted.Zeromeanswaitindefinitely.Settingany positivevaluewillcausethegetConnection()calltotime-outandbreakwithanSQLException afterthespecifiednumberofmilliseconds.


connectionCustomizerClassName

Default:null Thefullyqualifiedclass-nameofanimplememtationoftheConnectionCustomizer interface, whichuserscanimplementtosetupConnectionswhentheyareacquiredfromthedatabase,or oncheck-out,andpotentiallytocleanthingsuponcheck-inandConnectiondestruction.If standardConnectionproperties(holdability,readOnly,ortransactionIsolation)aresetinthe ConnectionCustomizer'sonAcquire()method,thesewilloverridetheConnectiondefaultvalues.


connectionTesterClassName

Default:com.mchange.v2.c3p0.impl.DefaultConnectionTester Thefullyqualifiedclass-nameofanimplememtationoftheConnectionTester interface,or QueryConnectionTester ifyouwouldlikeinstancestohaveaccesstoauser-configured preferredTestQuery .Thiscanbeusedtocustomizehowc3p0DataSourcestestConnections, butwiththeintroductionofautomaticTestTable andpreferredTestQuery configuration parameters,"rollingyourown"shouldbeoverkillformostusers.[See"ConfiguringConnection Testing"]
debugUnreturnedConnectionStackTraces

Default:false Iftrue,andifunreturnedConnectionTimeout issettoapositivevalue,thenthepoolwill capturethestacktrace(viaanException)ofallConnectioncheckouts,andthestacktraceswill beprintedwhenunreturnedchecked-outConnectionstimeout.Thisisintendedtodebug applicationswithConnectionleaks,thatisapplicationsthatoccasionallyfailtoreturn Connections,leadingtopoolgrowth,andeventuallyexhaustion(whenthepoolhitsmaxPoolSize withallConnectionschecked-outandlost).Thisparametershouldonlybesetwhiledebugging, ascapturingthestacktracewillslowdowneveryConnectioncheck-out.

21 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

DoesNotSupportPer-UserOverrides.
factoryClassLocation

Default:null DataSourcesthatwillbeboundbyJNDIandusethatAPI'sReferenceableinterfacetostore themselvesmayspecifyaURLfromwhichtheclasscapableofdereferencingathemmaybe loaded.If(asisusuallythecase)thec3p0librarieswillbelocallyavailabletotheJNDIservice, leavethissetasnull. DoesNotSupportPer-UserOverrides.


forceIgnoreUnresolvedTransactions

Default:false Stronglydisrecommended.Settingthistotrue mayleadtosubtleandbizarrebugs. Thisisaterriblesetting,leaveitaloneunlessabsolutelynecessary.Itisheretoworkaround brokendatabases/JDBCdriversthatdonotproperlysupporttransactions,butthatallow Connections'autoCommit flagstogotofalseregardless.Ifyouareusingadatabasethat supportstransactions"partially"(thisisoxymoronic,asthewholepointoftransactionsisto performoperationsreliablyandcompletely,butnonethelesssuchdatabasesareoutthere),if youfeelcomfortableignoringthefactthatConnectionswithautoCommit == false maybein themiddleoftransactionsandmayholdlocksandotherresources,youmayturnoffc3p0's wisedefaultbehavior,whichistoprotectitself,aswellastheusabilityandconsistencyofthe database,byeitherrollingback(default)orcommitting(seec3p0.autoCommitOnClose above) unresolvedtransactions.Thisshouldonlybesettotruewhenyouaresureyouareusing adatabasethatallowsConnections'autoCommitflagtogotofalse,butoffersnoother meaningfulsupportoftransactions.Otherwisesettingthistotrueisjustabadidea. [See"ConfiguringUnresolvedTransactionHandling"]
idleConnectionTestPeriod

Default:0 Ifthisisanumbergreaterthan0,c3p0willtestallidle,pooledbutunchecked-outconnections, everythisnumberofseconds.[See"ConfiguringConnectionTesting"]


initialPoolSize

Default:3 NumberofConnectionsapoolwilltrytoacquireuponstartup.ShouldbebetweenminPoolSize andmaxPoolSize .[See"BasicPoolConfiguration"]


maxAdministrativeTaskTime

Default:0 Secondsbeforec3p0'sthreadpoolwilltrytointerruptanapparentlyhungtask.Rarelyuseful. Manyofc3p0'sfunctionsarenotperformedbyclientthreads,butasynchronouslybyaninternal threadpool.c3p0'sasynchronyenhancesclientperformancedirectly,andminimizesthelength oftimethatcriticallocksareheldbyensuringthatslowjdbcoperationsareperformedin non-lock-holdingthreads.If,however,someofthesetasks"hang",thatistheyneithersucceed norfailwithanExceptionforaprolongedperiodoftime,c3p0'sthreadpoolcanbecome exhaustedandadministrativetasksbackedup.Ifthetasksaresimplyslow,thebestwayto resolvetheproblemistoincreasethenumberofthreads,vianumHelperThreads.Butiftasks sometimeshangindefinitely,youcanusethisparametertoforceacalltothetaskthread's interrupt() methodifataskexceedsasettimelimit.[c3p0willeventuallyrecoverfromhung tasksanywaybysignallingan"APPARENTDEADLOCK"(you'llseeitasawarninginthe logs),replacingthethreadpooltaskthreads,andinterrupt()ingtheoriginalthreads.Butletting thepoolgointoAPPARENTDEADLOCKandthenrecovermeansthatforsomeperiods,

22 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

c3p0'sperformancewillbeimpaired.Soifyou'reseeingthesemessages,increasing numHelperThreadsandsettingmaxAdministrativeTaskTime mighthelp. maxAdministrativeTaskTime shouldbelargeenoughthatanyresonableattempttoacquirea Connectionfromthedatabase,totestaConnection,ortwodestroyaConnection,wouldbe expectedtosucceedorfailwithinthetimeset.Zero(thedefault)meanstasksarenever interrupted,whichisthebestandsafestpolicyundermostcircumstances.Iftasksarejust slow,allocatemorethreads.Iftasksarehangingforever,trytofigureoutwhy,andmaybe settingmaxAdministrativeTaskTime canhelpinthemeantime. DoesNotSupportPer-UserOverrides.
maxConnectionAge

Default:0 Seconds,effectivelyatimetolive.AConnectionolderthanmaxConnectionAge willbe destroyedandpurgedfromthepool.ThisdiffersfrommaxIdleTime inthatitreferstoabsolute age.EvenaConnectionwhichhasnotbeenmuchidlewillbepurgedfromthepoolifitexceeds maxConnectionAge .Zeromeansnomaximumabsoluteageisenforced.


maxIdleTime

Default:0 SecondsaConnectioncanremainpooledbutunusedbeforebeingdiscarded.Zeromeansidle connectionsneverexpire.[See"BasicPoolConfiguration"]


maxIdleTimeExcessConnections

Default:0 NumberofsecondsthatConnectionsinexcessofminPoolSize shouldbepermittedtoremain idleinthepoolbeforebeingculled.Intendedforapplicationsthatwishtoaggressivelyminimize thenumberofopenConnections,shrinkingthepoolbacktowardsminPoolSizeif,followinga spike,theloadleveldiminishesandConnectionsacquiredarenolongerneeded.IfmaxIdleTime isset,maxIdleTimeExcessConnections shouldbesmalleriftheparameteristohaveany effect.Zeromeansnoenforcement,excessConnectionsarenotidledout.


maxPoolSize

Default:15 MaximumnumberofConnectionsapoolwillmaintainatanygiventime.[See"BasicPool Configuration"]


maxStatements

Default:0 Thesizeofc3p0'sglobalPreparedStatementcache.IfbothmaxStatements and maxStatementsPerConnection arezero,statementcachingwillnotbeenabled.If maxStatements iszerobut maxStatementsPerConnection isanon-zerovalue,statement cachingwillbeenabled,butnogloballimitwillbeenforced,onlytheper-connectionmaximum. maxStatements controlsthetotalnumberofStatementscached,forallConnections.Ifset,it shouldbeafairlylargenumber,aseachpooledConnectionrequiresitsown,distinctflockof cachedstatements.Asaguide,considerhowmanydistinctPreparedStatementsareused frequentlyinyourapplication,andmultiplythatnumberbymaxPoolSize toarriveatan appropriatevalue.ThoughmaxStatements istheJDBCstandardparameterforcontrolling statementcaching,usersmayfindc3p0'salternativemaxStatementsPerConnection more intuitivetouse.[See"ConfiguringStatementPooling"]
maxStatementsPerConnection

23 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Default:0 ThenumberofPreparedStatementsc3p0willcacheforasinglepooledConnection.Ifboth maxStatements and maxStatementsPerConnection arezero,statementcachingwillnotbe enabled.IfmaxStatementsPerConnection iszerobutmaxStatements isanon-zerovalue, statementcachingwillbeenabled,andagloballimitenforced,butotherwisenolimitwillbeset onthenumberofcachedstatementsforasingleConnection.Ifset, maxStatementsPerConnectionshouldbesettoaboutthenumberdistinctPreparedStatements thatareusedfrequentlyinyourapplication,plustwoorthreeextrasoinfrequentlystatements don'tforcethemorecommoncachedstatementstobeculled.ThoughmaxStatements isthe JDBCstandardparameterforcontrollingstatementcaching,usersmayfind maxStatementsPerConnection moreintuitivetouse.[See"ConfiguringStatementPooling"]
minPoolSize

Default:3 MinimumnumberofConnectionsapoolwillmaintainatanygiventime.[See"BasicPool Configuration"]


numHelperThreads

Default:3 c3p0isveryasynchronous.SlowJDBCoperationsaregenerallyperformedbyhelperthreads thatdon'tholdcontendedlocks.Spreadingtheseoperationsovermultiplethreadscan significantlyimproveperformancebyallowingmultipleoperationstobeperformed simultaneously. DoesNotSupportPer-UserOverrides.


overrideDefaultUser

Default:null ForcestheusernamethatshouldbyPooledDataSourceswhenausercallsthedefault getConnection()method.ThisisprimarilyusefulwhenapplicationsarepoolingConnectionsfrom anon-c3p0unpooledDataSource.ApplicationsthatuseComboPooledDataSource ,orthatwrap anyc3p0-implementedunpooledDataSourcecanusethesimpleuserproperty. DoesNotSupportPer-UserOverrides.


overrideDefaultPassword

Default:null ForcesthepasswordthatshouldbyPooledDataSourceswhenausercallsthedefault getConnection()method.ThisisprimarilyusefulwhenapplicationsarepoolingConnectionsfrom anon-c3p0unpooledDataSource.ApplicationsthatuseComboPooledDataSource ,orthatwrap anyc3p0-implementedunpooledDataSourcecanusethesimplepasswordproperty. DoesNotSupportPer-UserOverrides.


password

Default:null ForapplicationsusingComboPooledDataSource oranyc3p0-implementedunpooled DataSourcesDriverManagerDataSource ortheDataSourcereturnedby DataSources.unpooledDataSource( ... ) definesthepasswordthatwillbeusedforthe DataSource'sdefaultgetConnection() method.(Seealsouser.) DoesNotSupportPer-UserOverrides.
preferredTestQuery

24 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Default:null Definesthequerythatwillbeexecutedforallconnectiontests,ifthedefaultConnectionTester (orsomeotherimplementationofQueryConnectionTester,orbetteryet FullQueryConnectionTester)isbeingused.DefiningapreferredTestQuery thatwillexecute quicklyinyourdatabasemaydramaticallyspeedupConnectiontests.(Ifno preferredTestQuery isset,thedefaultConnectionTesterexecutesa getTables() callonthe Connection'sDatabaseMetaData.Dependingonyourdatabase,thismayexecutemoreslowly thana"normal"databasequery.)NOTE:ThetableagainstwhichyourpreferredTestQuery willberunmustexistinthedatabaseschemapriortoyourinitializationofyour DataSource.Ifyourapplicationdefinesitsownschema,tryautomaticTestTable instead.[See"ConfiguringConnectionTesting"]
propertyCycle

Default:0 Maximumtimeinsecondsbeforeuserconfigurationconstraintsareenforced.Determineshow frequentlymaxConnectionAge ,maxIdleTime ,maxIdleTimeExcessConnections , unreturnedConnectionTimeout areenforced.c3p0periodicallycheckstheageofConnections toseewhetherthey'vetimedout.Thisparameterdeterminestheperiod.Zeromeansautomatic: Asuitableperiodwillbedeterminedbyc3p0.[YoucancallgetEffectivePropertyCycle...() methodsonac3p0PooledDataSourcetofindtheperiodautomaticallychosen.]
testConnectionOnCheckin

Default:false Iftrue,anoperationwillbeperformedasynchronouslyateveryconnectioncheckintoverifythat theconnectionisvalid.UseincombinationwithidleConnectionTestPeriod forquitereliable, alwaysasynchronousConnectiontesting.Also,settinganautomaticTestTable or preferredTestQuery willusuallyspeedupallconnectiontests.[See"ConfiguringConnection Testing"]


testConnectionOnCheckout

Default:false Useonlyifnecessary.Expensive.Iftrue,anoperationwillbeperformedateveryconnection checkouttoverifythattheconnectionisvalid.Betterchoice:verifyconnectionsperiodically usingidleConnectionTestPeriod .Also,settinganautomaticTestTable or preferredTestQuery willusuallyspeedupallconnectiontests.[See"ConfiguringConnection Testing"]


unreturnedConnectionTimeout

Default:0 Seconds.Ifset,ifanapplicationchecksoutbutthenfailstocheck-in[i.e.close()]aConnection withinthespecifiedperiodoftime,thepoolwillunceremoniouslydestroy()theConnection.This permitsapplicationswithoccasionalConnectionleakstosurvive,ratherthaneventually exhaustingtheConnectionpool.Andthat'sashame.Zeromeansnotimeout,applicationsare expectedtoclose()theirownConnections.Obviously,ifanon-zerovalueisset,itshouldbeto avaluelongerthananyConnectionshouldreasonablybechecked-out.Otherwise,thepoolwill occasionallykillConnectionsinactiveuse,whichisbad.Thisisbasicallyabadidea,butit's acommonlyrequestedfeature.Fixyour$%!@%applicationssotheydon'tleak Connections!Usethistemporarilyincombinationwith debugUnreturnedConnectionStackTraces tofigureoutwhereConnectionsarebeing checked-outthatdon'tmakeitbackintothepool!
user

25 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Default:null ForapplicationsusingComboPooledDataSource oranyc3p0-implementedunpooled DataSourcesDriverManagerDataSource ortheDataSourcereturnedby DataSources.unpooledDataSource() definestheusernamethatwillbeusedforthe DataSource'sdefaultgetConnection() method.(Seealsopassword.) DoesNotSupportPer-UserOverrides.
usesTraditionalReflectiveProxies

Default:false c3p0originallyusedreflectivedynamicproxiesforimplementationsofConnectionsandother JDBCinterfaces.Asofc3p0-0.8.5,non-reflective,code-generatedimplementationsareused instead.Asthiswasamajorchange,andtheoldcodebasehadbeenextensivelyusedand tested,thisparameterwasaddedtoallowuserstorevertoftheyhadproblems.Thenew, non-reflexiveimplementationisfaster,andhasnowbeenwidelydeployedandtested,soitis unlikelythatthisparameterwillbeuseful.Boththeoldreflectiveandnewernon-reflective codebasesarebeingmaintained,butsupportfortheoldercodebasemay(ormaynot)be droppedinthefuture.

OtherProperties
Thefollowingconfigurationpropertiesaffectthebehaviorofthec3p0libraryasawhole.They maybesetassystemproperties,orinac3p0.propertiesfile.

Logging-relatedproperties The following properties affect c3p0's logging behavior. Please see Configuring Loggingaboveforspecificinformation.
com.mchange.v2.log.MLog com.mchange.v2.log.NameTransformer com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL

ConfiguringJMX The following property controls c3p0's JMX management interface. Plese see ConfiguringandManagingc3p0viaJMXaboveformoreinformation.
com.mchange.v2.c3p0.management.ManagementCoordinator

ConfiguringtheVMID Isitbettertobebeautifulorcorrect?Beginningwithc3p0-0.9.1,c3p0optssomewhat reluctantlyforcorrectness. Here'sthedeal.Everyc3p0DataSourceisallocatedaunique"identitytoken",which isusedtoensurethatmultipleJNDIlookupsofthesamePooledDataSourcealways return the same instance, even if the JNDI name-server stores a Serialized or Referencedinstance.Previously,c3p0washappyforgeneratedIDstobeunique

26 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

withinasingleVM(anditdidn'tevengetthatquiteright,beforec3p0-0.9.1).Butin theory,oneVMmightlookuptwodifferentDataSources,generatedbytwodifferent VMs,thatbyunlikelycoincidencehavethesame"identitytoken",leadingtoerrorsas one of the two DataSources sneakily substitutes for the second. Though this hypothetical issue has never been reported in practice, c3p0 resolves it by prependingaVMIDtoitsidentitytokens.Thismakesthemlongandugly,butcorrect. Ifyoudon'tlikethelonganduglyVMID,youcansetyourown,oryoucanturnoffthis solutiontoahypotheticalnon-problementirelywiththefollowingproperty:
com.mchange.v2.c3p0.VMID

SetittoNONEtoturnofftheVMID,setittoAUTOtoletc3p0generateaVMID,orprovide anyotherStringtosettheVMIDthatwillbeuseddirectly.ThedefaultisAUTO. Experimentalproperties c3p0-0.9.1includesanewimplementationofasynchronousConnectionacquisition thatshould improve c3p0's performance and resource utilization in cases where database acquisition attempts, for whatever reason, occasionally fail. The new implementation should be significantly better than the "traditional" Connection acquisitionstrategy,butwasaddedtoolateinthec3p0-0.9.1developmentcycleto be fully tested and enabled by default. Users are encouraged to try the new implementation,both because itisbetter,and to help iron outanyunanticipated problems. Fora full description ofthe new implementation and the resource bottleneckitis designedtoovercome,pleaseseetheCHANGELOGentryforc3p0-0.9.1-pre11.Toenable thenewimplementation,setthefollowingparameterto"true".
com.mchange.v2.resourcepool.experimental.useScatteredAcquireTask

Thisfeatureisexpectedtobeenabledbydefaultinc3p0-0.9.2andabove.

AppendixB:ConfigurationFiles,etc.
c3p0configurationparameterscanbesetdirectlyinJavacode,viaasimpleJavaproperties file,viaanXMLconfigurationfile,orviaSystemproperties.Anywhichwayworks(thethe XMLconfigurationismostpowerful,though,asitsupportsmultiplenamedconfigurationsand per-useroverrides.Choosewhateverworksbestforyou.

Overridingc3p0defaultsviac3p0.properties
Tooverridethelibrary'sbuilt-indefaults,createafilecalledc3p0.propertiesandplaceitatthe
27 de 34 23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

"root"ofyourclasspathorclassloader.Foratypicalstandaloneapplication,thatmeansplace thefileinadirectorynamedinyourCLASSPATHenvironmentvariable.Foratypical web-application,thefileshouldbeplacedinWEB-INF/classes.Ingeneral,thefilemustbe availableasaclassloaderresourceunderthename/c3p0.properties,intheclassloaderthat loadedc3p0'sjarfile.ReviewtheAPIdocs(especillygetResource...methods)of java.lang.Class,java.lang.ClassLoader,andjava.util.ResourceBundleifthisisunfamiliar. Theformatofc3p0.propertiesshouldbeanormalJavaPropertiesfileformat,whosekeysare c3p0configurableproperties.SeeAppendixA.forthespecifics.Anexamplec3p0.properties fileisproducedbelow:

# turn on statement pooling c3p0.maxStatements=150 # close pooled Connections that go unused for # more than half an hour c3p0.maxIdleTime=1800

Overridingc3p0defaultswithaSystemproperties
c3p0propertiescanalsobedefinedasSystemproperties,usingthesame"c3p0."prefixfor propertiesspecifiedinac3p0.propertiesfile.

swaldman% java -Dc3p0.maxStatements=150 -Dc3p0.maxIdleTime=1800 example.MyC3P0App

Systempropertiesoverridesettingsinc3p0.properties.PleaseseePrecedenceof ConfigurationSettingsformoreinformation.

NamedandPer-Userconfiguration:Overridingc3p0defaultsvia
c3p0-config.xml

Asofc3p0-0.9.1,youcandefinemultipleconfigurationsinanXMLconfigurationfile,and specifyinyourcodewhichconfigurationtouse.Foranyconfigurations(includingthe unnameddefaultconfiguration),youcandefineoverridesforaparticulardatabaseuser.For example,ifseveralapplicationsaccessyourdatabaseunderdifferentauthentication credentials,youmightdefinemaxPoolSizetobe100foruserhighVolumeApp,butonly10foruser lowLoadApp.(RecallthatConnectionsassociatedwithdifferentauthenticationcredentialsareof necessityseparatedintoseparatepools,soitmakessensethatthesecouldbeconfigured separately.) YoucanusetheXMLconfigfileforallc3p0configuration,includingconfigurationofdefaults. However,foruserswhodon'twantorneedtheextracomplexity,thec3p0.propertiesfilewill continuetobesupported.

28 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

Bydefault,c3p0willlookforanXMLconfigurationfileinitsclassloader'sresourcepathunder thename"/c3p0-config.xml".ThatmeanstheXMLfileshouldbeplacedinadirectlyorjarfile directlynamedinyourapplicationsCLASSPATH,inWEB-INF/classes,orsomesimilar location.Ifyouprefernottobundleyourconfigurationwithyourcode,youcanspecifyan ordinaryfilesystemlocationforc3p0'sconfigurationfileviathesystemproperty com.mchange.v2.c3p0.cfg.xml. Hereisanexamplec3p0-config.xmlfile:

<c3p0-config> <default-config> <property name="automaticTestTable">con_test</property> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> <user-overrides user="test-user"> <property name="maxPoolSize">10</property> <property name="minPoolSize">1</property> <property name="maxStatements">0</property> </user-overrides> </default-config> <!-- This app is massive! --> <named-config name="intergalactoApp"> <property name="acquireIncrement">50</property> <property name="initialPoolSize">100</property> <property name="minPoolSize">50</property> <property name="maxPoolSize">1000</property> <!-- intergalactoApp adopts a different approach to configuring statement caching --> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him --> <user-overrides user="master-of-the-universe"> <property name="acquireIncrement">1</property> <property name="initialPoolSize">1</property> <property name="minPoolSize">1</property> <property name="maxPoolSize">5</property> <property name="maxStatementsPerConnection">50</property> </user-overrides> </named-config> </c3p0-config>

Touseanamedconfiguration,youspecifytheconfignamewhencreatingyourDataSource. Forexample,usingComboPooledDataSource:

ComboPooledDataSource cpds = new ComboPooledDataSource("intergalactoApp");

OrusingtheDataSourcesfactoryclass:

29 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoApp" );

PrecedenceofConfigurationSettings
c3p0nowpermitsconfigurationparameterstobesetinanumberofdifferentwaysand places.Fortunately,thereisaclearorderofprecedencethatdetermineswhichconfiguration will"take"intheeventofconflictingsettings.Conceptually,c3p0goesdownthislistfromtop tobottom,usingthefirstsettingitfinds. Mostapplicationswillneveruseper-userornamedconfigurations.Fortheseapplications,we presentasimplifiedprecedencehierarchy:

1. Configurationvaluesprogrammaticallyset. 2. Systempropertysettingofconfigurationvalue. 3. Configurationvaluestakenfromthedefaultconfigurationofac3p0-config.xml file. 4. Configurationvaluesspecifiedinac3p0.properties file 5. c3p0'shard-codeddefaultvalues.

Forapplicationsthatdousenamedandper-userconfigurations,hereisthecomplete, normativeprecedencehierarchy:

1. User-specificoverridesprogrammaticallysetvia:
ComboPooledDataSource.setUserOverridesAsString() WrapperConnectionPoolDataSource.setUserOverridesAsString()

Notethatprogrammaticallysettinguser-specificoverridesreplacesalluser-specific configurationtakenfromothersources.Ifyouwanttomergeprogrammaticchangeswith preconfiguredoverrides,you'llhavetousegetUserOverridesAsString() andmodifythe originalsettingsbeforereplacing. 2. User-specificoverridestakenfromaDataSource'snamedconfiguration(specifiedin c3p0-config.xml ) 3. User-specificoverridestakenfromthedefaultconfiguration(specifiedin c3p0-config.xml ) 4. Non-user-specificvaluesprogrammaticallyset. 5. Non-user-specificvaluestakenfromaDataSource'snamedconfiguration(specifiedin c3p0-config.xml ) 6. Systempropertysettingofconfigurationvalue. 7. Non-user-specificvaluestakenfromthedefaultconfiguration(specifiedin c3p0-config.xml ) 8. Valuesspecifiedinac3p0.properties file 9. c3p0'shard-codeddefaultvalues.

30 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

AppendixC:Hibernate-specificnotes
Hibernate'sC3P0ConnectionProviderexplicitlysets7c3p0configurationproperties,based onyourhibernateconfiguration,overridinganyconfigurationyoumayhavesetina c3p0.propertiesfile.IfyouareusingHibernate'sC3P0ConnectionProvideryoumustsetthe followingpropertiesinyourhibernateconfiguration,usinghibernate-specificconfiguration keys.Allotherpropertiesmustbedefinedasusualinac3p0.propertiesfile.Thisisconfusing, andwillhopefullybesimplifiedsometimeinthefuture,butfornow... Thefollowingpropertiesmustbesetinyourhibernateconfiguration:
c3p0-nativepropertyname
c3p0.acquireIncrement c3p0.idleConnectionTestPeriod c3p0.initialPoolSize c3p0.maxIdleTime c3p0.maxPoolSize c3p0.maxStatements c3p0.minPoolSize c3p0.testConnectionsOnCheckout

hibernateconfigurationkey
hibernate.c3p0.acquire_increment hibernate.c3p0.idle_test_period notavailable--usesminimumsize hibernate.c3p0.timeout hibernate.c3p0.max_size hibernate.c3p0.max_statements hibernate.c3p0.min_size hibernate.c3p0.validate hibernate2.xonly!

Remember--these,andonlythese,propertiesmustbedefinedinyourhibernate configuration,orelsetheywillbesettohibernate-specifieddefaults.Allotherconfiguration propertiesthatyouwishtosetshouldbedefinedinac3p0.propertiesfile.(See"Overriding c3p0defaultsviac3p0.properties".)

AppendixD:Configuringc3p0DataSourcesinTomcat
YoucaneasilyconfigureApache'sTomcatwebapplicationservertousec3p0pooled DataSources.BelowisaTomcat5.0sampleconfigtogetyoustarted.It'safragmentof Tomcat'sconf/server.xmlfile,whichshouldbemodifiedtosuitandplacedinsidea<Context> element.

<Resource name="jdbc/pooledDS" auth="Container" type="com.mchange.v2.c3p0.ComboPooledDataSource" /> <ResourceParams name="jdbc/pooledDS"> <parameter> <name>factory</name> <value>org.apache.naming.factory.BeanFactory</value> </parameter> <parameter> <name>driverClass</name> <value>org.postgresql.Driver</value> </parameter> <parameter> <name>jdbcUrl</name> <value>jdbc:postgresql://localhost/c3p0-test</value> </parameter> <parameter> <name>user</name> <value>swaldman</value> </parameter>

31 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...


<parameter> <name>password</name> <value>test</value> </parameter> <parameter> <name>minPoolSize</name> <value>5</value> </parameter> <parameter> <name>maxPoolSize</name> <value>15</value> </parameter> <parameter> <name>acquireIncrement</name> <value>5</value> </parameter> </ResourceParams>

http://www.mchange.com/projects/c3p0/index.html

ForTomcat5.5,trysomethinglikethefollowing(thankstoCarlF.Hallforthesample!):

<Resource auth="Container" description="DB Connection" driverClass="com.mysql.jdbc.Driver" maxPoolSize="4" minPoolSize="2" acquireIncrement="1" name="jdbc/TestDB" user="test" password="ready2go" factory="org.apache.naming.factory.BeanFactory" type="com.mchange.v2.c3p0.ComboPooledDataSource" jdbcUrl="jdbc:mysql://localhost:3306/test?autoReconnect=true" />

TherestisstandardJ2EEstuff:You'llneedtodeclareyourDataSourcereferenceinyour web.xmlfile:

<resource-ref> <res-ref-name>jdbc/pooledDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>

AndyoucanaccessyourDataSourcefromcodewithinyourwebapplicationlikethis:

InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/pooledDS");

That'sit!

32 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

AppendixE:JBoss-specificnotes
Tousec3p0withJBoss: 1. Placec3p0'sjarfileinthelibdirectoryofyourjbossserverinstance(e.g. ${JBOSS_HOME}/server/default/lib) 2. Modifythefilebelow,andsaveitasc3p0-service.xmlinthedeploydirectoryofyourjboss server(e.g.${JBOSS_HOME}/server/default/deploy).Notethatparametersmustbecapitalized inthisfile,butotherwisetheyaredefinedasdescribedabove. Note:Usersofc3p0jbosssupportpriortoc3p0-0.9.1pleaseclickhere!

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE server> <server> <mbean code="com.mchange.v2.c3p0.jboss.C3P0PooledDataSource" name="jboss:service=C3P0PooledDataSource"> <attribute <attribute <attribute <attribute <attribute name="JndiName">java:PooledDS</attribute> name="JdbcUrl">jdbc:postgresql://localhost/c3p0-test</attribute> name="DriverClass">org.postgresql.Driver</attribute> name="User">swaldman</attribute> name="Password">test</attribute>

<!-- Uncomment and set any of the optional parameters below --> <!-- See c3p0's docs for more info. --> <!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<!-<attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute <attribute name="AcquireIncrement">3</attribute> name="AcquireRetryAttempts">30</attribute> name="AcquireRetryDelay">1000</attribute> name="AutoCommitOnClose">false</attribute> name="AutomaticTestTable"></attribute> name="BreakAfterAcquireFailure">false</attribute> name="CheckoutTimeout">0</attribute> name="ConnectionCustomizerClassName"></attribute> name="ConnectionTesterClassName"></attribute> name="Description">A pooled c3p0 DataSource</attribute> name="DebugUnreturnedConnectionStackTraces">false</attribute> name="FactoryClassLocation"></attribute> name="ForceIgnoreUnresolvedTransactions">false</attribute> name="IdleConnectionTestPeriod">0</attribute> name="InitialPoolSize">3</attribute> name="MaxAdministrativeTaskTime">0</attribute> name="MaxConnectionAge">0</attribute> name="MaxIdleTime">0</attribute> name="MaxIdleTimeExcessConnections">0</attribute> name="MaxPoolSize">15</attribute> name="MaxStatements">0</attribute> name="MaxStatementsPerConnection">0</attribute> name="MinPoolSize">0</attribute> name="NumHelperThreads">3</attribute> name="PreferredTestQuery"></attribute> name="TestConnectionOnCheckin">false</attribute> name="TestConnectionOnCheckout">false</attribute> name="UnreturnedConnectionTimeout">0</attribute> name="UsesTraditionalReflectiveProxies">false</attribute> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> -->

<depends>jboss:service=Naming</depends> </mbean> </server>

33 de 34

23/09/11 10:54

c3p0-v0.9.1.1 - JDBC3 Connection and Statement P...

http://www.mchange.com/projects/c3p0/index.html

AppendixF:Oracle-specificAPI:createTemporaryBLOB()and createTemporaryCLOB()
TheOraclethinJDBCdriverprovidesanon-standardAPIforcreatingtemporaryBLOBsand CLOBsthatrequiresuserstocallmethodsontheraw,Oracle-specificConnection implementation.Advancedusersmightusetherawconnectionoperationsdescribedabove toaccessthisfunctionality,butaconvenienceclassisavailableinaseparatejarfile(c3p0oracle-thin-extras-0.9.1.1.jar)foreasieraccesstothisfunctionality.PleaseseetheAPIdocs forcom.mchange.v2.c3p0.dbms.OracleUtilsfordetails. BacktoContents

34 de 34

23/09/11 10:54

Das könnte Ihnen auch gefallen