Java Reference
In-Depth Information
essentially a big pool of reusable objects. Java EE, meanwhile, depends on object pools for
connections to databases and other resources, and the entire lifecycle of Enterprise Java
Beans is built around the notion of an object pool.
The situation is similar for thread-local values; the JDK is filled with classes that use thread-
local variables to avoid reallocating certain kinds of objects.
Clearly, even Java experts understand the need for object reuse in some circumstances.
The reason for reusing objects is that many objects are quite expensive to initialize, and reus-
ing them is more efficient than the trade-off in increased GC time. That is certainly true of
things like the JDBC connection pool: creating the network connection, and possibly logging
in and establishing a database session, is quite expensive. Object pooling in that case is a big
performance win. Threads are pooled to save the time associated with creating a thread; ran-
dom number generators are supplied as thread-local variables to save the time require to seed
them; and so on.
One feature these examples share is that it takes a long time to initialize the object. In Java,
object allocation is quite fast and inexpensive (and arguments against object reuse tend to fo-
cus on that part of the equation). Object initialization performance depends on the object.
You should only consider reusing objects with a very high initialization cost, and only then if
the cost of initializing those objects is one of the dominant operations in your program.
Another feature these examples share is that the number of shared objects tends to be small,
which minimizes their impact on GC operations: there aren't enough of them to slow down
those GC cycles. Having a few objects in a pool isn't going to affect the GC efficiency too
much; filling the heap with pooled objects will slow down GC significantly.
Here are just some examples of where (and why) the JDK and Java EE reuse objects:
Thread pools
Threads are expensive to initialize.
JDBC pools
Database connections are expensive to initialize.
EJB pools
EJBs can be expensive to initialize (see Chapter 10 ).
Search WWH ::

Custom Search