The Artima Developer Community
Sponsored Link

Josh Bloch on Design
A Conversation with Effective Java Author, Josh Bloch
by Bill Venners
First Published in JavaWorld, January 4, 2002

<<  Page 16 of 19  >>


Lightweight versus Heavyweight Objects

Bill Venners: In your book, you say it's usually not a good idea to do object pooling for lightweight objects, because the VM is very efficient at garbage collecting lightweight objects. By "lightweight" do you mean it doesn't take much time to construct the object, or the object doesn't take much memory? Define heavyweight versus lightweight object.

Josh Bloch: I really do mean time. But on the other hand, if it takes a lot of memory, it probably takes a lot of time, because you are initializing all that memory. Basically the idea is that you'd like to amortize the work when you've made a heavyweight object. The canonical example is a database connection, where you do all sorts of native calls to establish the session. And it can take a major fraction of a second (or more) to do this. It would be silly to use it for a few calls, discard it, and then spend that time again to do a few more calls the next time someone needs to access the database. You should decide up front how much resources you want to allocate to this. You should create, say, five open connections, or whatever. You should have this pool of connections and just share them among all of the clients.

It's more about computation time than it is about memory. I'm not an expert in this area, but the people in the 2D graphics community talk about pooling frame buffers as well, where there are huge quantities of memory involved (megabytes). It's also about predictability. If something is big, and you have strict bounds on how many you will need, it might be reasonable to leave them around and pool them yourself.

<<  Page 16 of 19  >>

Sponsored Links

Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use