Lecture 6
Lecture 6
Lecture - 6
• Delegating constructors
• Uninstantiable classes
Example
Example
Garbage Collection
• Since objects are dynamically allocated by using
the new operator, you might be wondering how
such objects are destroyed and their memory
released for later reallocation.
• In some languages, such as traditional C++,
dynamically allocated objects must be manually
released by use of a delete operator.
• Java does it automatically.
• The technique that accomplishes this is called
Garbage Collection.
How Garbage Collection Works
• It works like this:
• when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be
reclaimed.
• There is no need to explicitly destroy objects.
• Garbage collection only occurs sporadically (if at all) during the
execution of your program.
• It will not occur simply because one or more objects exist that are no
longer used.
• Furthermore, different Java run-time implementations will take
varying approaches to garbage collection, but for the most part, you
should not have to think about it while writing your programs.
Garbage Collection
• Since objects are dynamically allocated by using
the new operator, you might be wondering how
such objects are destroyed and their memory
released for later reallocation.
• In some languages, such as traditional C++,
dynamically allocated objects must be manually
released by use of a delete operator.
• Java does it automatically.
• The technique that accomplishes this is called
Garbage Collection.
Ways to make an object eligible for garbage collection in Java-
This makes the useless objects automatically eligible for the purpose of
garbage collection.
Ways to make an object eligible for garbage collection in Java-
• 4. Island of Isolation-
• Island of Isolation describes the situation where there exists
one or more objects in the program which are not accessible
from anywhere in the application as they contain no external
reference to them.
• It is not possible to access such objects through any means as
they have no external reference to them and thus they become
eligible for garbage collection.
• So, it appears as if the objects are stuck on some isolated island
and they can not be accessed through any means. Hence, the
name “Island of Isolation” is quite apt.
Ways to make an object eligible for garbage collection in Java-
• 4. Island of Isolation-Example
1. class Demo
2. {
3. Demo d;
4.
5. public static void main(string[ ] args)
6. {
7. Demo d1 = new Demo( );
8. Demo d2 = new Demo( );
9. Demo d3 = new Demo( );
10. .
11. .
12. d1.d = d2;
13. d2.d = d3;
14. d3.d = d1;
15. .
16. d1 = null;
17. d2 = null;
18. d3 = null;
19. }
20. }