1. Connections are expensive objects to initialize; they are routinely pooled in
Java—either in the JDBC driver itself, or within Java EE and JPA frameworks.
2. As with other object pools, it is important to tune the connection pool so it doesn't
adversely affect the garbage collector. In this case, it is also necessary to tune the
connection pool so it doesn't adversely affect the performance of the database it-
Applications have correctness requirements that ultimately dictate how transactions are
handled. A transaction that requires repeatable-read semantics will be slower than a transac-
tion that requires only read-committed semantics, but knowing that is of little practical bene-
fit for an application that cannot tolerate nonrepeatable reads. So while this section discusses
how to use the least intrusive isolation semantics for an application, don't let the desire for
speed overcome the correctness of the application.
Database transactions have two performance penalties. First, it takes time for the database to
set up and then commit the transaction. This involves making sure that changes to the data-
base are fully stored on disk, that the database transaction logs are consistent, and so on. Se-
cond, during a database transaction, it is quite common for the transaction to obtain a lock
for a particular set of data (not always a row, but I'll use that as the example here). If two
transactions are contending for a lock on the same database row, then the scalability of the
application will suffer. From a Java perspective, this is exactly analogous to the discussion in
Chapter 9 about contended and uncontended locks.
For optimal performance, consider both of these issues: how to program the transactions so
that the transaction itself is efficient, and how to hold locks on the database during a transac-
tion so that the application as a whole can scale.
JDBC transaction control
Transactions are present within both JDBC and JPA applications, but JPA manages transac-
tions differently (those details are discussed later in this chapter). For JDBC, transactions be-
gin and end based on how the Connection object is used.