Object pooling : Java Glossary
- Object pooling
If you create large numbers of identical short-lived objects, you may be able to
allocate them faster using a manual method, rather than doing it with the standard
new and gc. There are three main dangers to recycling objects:
For a very simple, quick implementation, you simply put your no-longer needed
objects on a unidirectional recycle chain and when you need one, instead of using
new, you just allocate the head of the chain and remove the element from the chain.
If you start getting too many empties on your recycled chain, you just chop the
excess tail end of the chain off allow them to be garbage collected. You don’t
have to free them individually. If you run out of objects, use new to create some more. This technique is very powerful in
C++ but does not work as well in Java because Java has more efficient allocation techniques
- You must manually free each object when you are done with it. If you fail to do
so, you will have a memory leak. You are back to C++ manual alloc and free.
- It is totally up to you to ensure there are no links to an object you are about
- Constructors will not automatically be run to initialise objects freshly. You
must handle such code yourself, outside the constructor.