Java Reference
In-Depth Information
As discussed above, images are 'heavy' objects, which allocate large
native buffers containing the image data. It is extremely important to have
a well-defined image object lifecycle - essentially you must know when
to dispose of images you no longer need so that the native buffers can
be freed. Finally, if you need to load many images into memory before
starting your application, you should do so in another thread, to prevent
the blocking of the system thread.
9.2.5 Handle Exceptions
A fairly common mistake made by novice Java developers is declaring
their heavyweight resources (such as, connections or streams) inside a
try-catch block. For example, consider the following code sample.
// WRONG -
never do this!
try {
HttpConnection hc = (HttpConnection)Connector.open(url);
InputStream is = hc.openInputStream();
...
hc.close()
}
{
catch(Exception e)
// handle error
}
If an error occurs while reading the stream, we immediately leave the
scope of our try-catch block and are therefore unable to close the stream
and connection. Some implementations e.g., Java ME on Symbian OS,
may be able to recover using internal finalizers (if the implementation calls
finalizers and the finalizers for affected objects close native resources).
There are too many ifs and none of these behaviors are mandated by
MIDP or JSR specifications. Finally, although the implementation of Java
ME on Symbian OS has this level of resilience, there are no guarantees
on when the object is garbage collected. This kind of error counts as
relatively nasty resource leakage.
To be sure we clean up correctly, we can use the finally block as
follows.
HttpConnection hc = null;
InputStream is = null;
try {
hc = (HttpConnection)Connector.open(url);
is = conn.openInputStream();
...
}
catch(Exception e)
{
// handle error
}
finally {
if ( is != null )
{
try { is.close(); } catch(Exception e) {} }
if ( hc != null )
{
try { hc.close(); } catch(Exception e) {} }
}
Search WWH ::




Custom Search