1
votes

I have been using Tomcat for a while. But I have never get myself fully educated about how it actually works, especially thread pooling and JDBC connection pooling.

Take a standard Spring web app (with c3p0 connection pool) for example. My questions are

  1. When TC starts up, does it create N threads, each with an applicationContext?

  2. If so, does it mean each thread will have its own list of bean instances created?

  3. One of the bean definition is

<bean id="dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  <property name="driverClass" value="${db.driverClassName}"/>
  <property name="jdbcUrl" value="${db.url}"/>
  <property name="user" value="${db.username}"/>
  <property name="password" value="${db.password}"/>
  <property name="minPoolSize" value="5" />
</bean>

This will create 5 JDBC connections when this bean is created. Does it mean we are gonna end up with

5 connections x N threads = 5N connections?

This does not sound right to me. I thought the JDBC pool is shared across all threads. But apparently the JDBC pool (defined as a ComboPooledDataSource bean) is created as part of the applicationContext, right?

1

1 Answers

4
votes

When TC starts up, does it create N threads, each with an applicationContext?

No, it creates just one context with all the beans available for each and every thread within that web application. This means Spring beans (singleton by default) need to be thread safe since they are typically accessed concurrently by several threads. That's fine because normally Spring beans are stateless and thus thread-safe by definition.

Moreover there is only one JDBC connection pool holding 5 connections. All Tomcat web threads (and others, if created) compete for these 5 connections.

Therefore your remaining questions are no longer relevant. What makes you think Spring creates contexts for every thread?