Search code examples
javaoopeffective-java

Is terminating an object is the same as nulling it?


So i have been going through "Effective Java 2nd Ed."

In item 7 he talks about not using finalizers because they can cause a lot of problems .

But instead of using finalizers we can " provide an explicit termination method" and an example of those is the close statement . and i did not understand what is " termination statements and what are the differences between them and finalizers ?

I came to the conclusion that terminating an object is like nulling it thus the resourses is released . but i think i don`t understand the difference that well . so i appreciate any help .

Thanks !


Solution

  • But instead of using finalizers we can " provide an explicit termination method" and an example of those is the close statement .

    The authors refers to a close() method that provides a way to clean an object that uses resources to free.

    For example when you create and manipulate an InputStream or an OutputStream, you don't want to rely on Java finalizers (that may exist for some subclasses of these interface. For example it is the case for the FileInputStream class that defines a finalize() method) to release the resources associated to the stream but you want to use the method provided by the API to do it : void close() as it is more reliable as finalizer.

    java.sql.Statement works in the same way : it provides a close() method to release JDBC resources associated to the statement instance.

    I came to the conclusion that terminating an object is like nulling it thus the resourses is released .

    Assigning an object to null will not necessary free all resources that should be freed. Besides if the object or a field of the object is still referenced by another living object, the object would be not illegible to be garbage collected

    At last, being garbage collected may also take a some time.
    Why wait if we don't need to use the object ?