Java Reference
In-Depth Information
used to keep copies of the string. Always keep in mind, however, that
once interned, the string is never garbage collected.
9.2.3 Manage Objects Carefully
Java offers great benefits for developers by providing garbage collection.
It is, however, still necessary to take care when managing objects.
First, let us reiterate the rules. An object becomes eligible for garbage
collection when there are no references to it in any of the 'alive' threads.
In essence, this translates either to objects going out of scope (e.g.
local variables) or to setting class-scoped variables to NULL when we
don't expect them to be used any more. It is important to note that
a Java object may be associated with a native peer with high native
memory consumption (e.g., graphical and UI elements). The allocated
native memory, which is outside the Java object heap, is not freed and
made accessible to native applications until the associated Java object is
discarded and garbage collected.
For example, consider the MIDlet startup example in Section 9.1.2.
First, let us consider the lifecycle of the MyThread instance ( loader )
created in startApp() . Being declared inside a method, loader imme-
diately falls out of scope of the current thread. However, it is a reference to
a running thread and is not eligible for garbage collection. Once loader
is complete however, the MyThread object is not reachable by any
further running threads and is therefore eligible for garbage collection.
Now consider our use of SplashScreen . Since we never need the
SplashScreen instance after our MIDlet has started (once the Menu-
View has been initialized and set as the current screen), we discard our
class-scope reference to make the SplashScreen instance eligible for
garbage collection. The benefit of doing this may be small for lightweight
objects, however our SplashScreen is likely to have had references
to Image objects, e.g. for off-screen drawing, and it could amount to
significant memory savings.
One important technique for managing objects is to use object
pools. A pool is essentially a collection of reusable objects. Instead of a
create-use-discard cycle for an object, we may obtain one from a pool,
use it and then release it back to the pool for further usage. In doing so,
we have potentially saved some time in object creation and initialization
as well as reducing the garbage collection load. Pools are extremely
helpful, typically, for managing reusable network connections or objects
that are frequently created and destroyed (e.g. buffers). A simple pool
implementation is shown in the code sample below:
public class BufferPool
byte [][] buffers;
int count = 0;
int defaultBufferSize;
Search WWH ::

Custom Search