| Objective 1:Summary of Garbage Collection |
One of the most important features of the Java is garbage collection, also called automatic memory management. In Java while the program is running, the memory is being allocated withnewoperation. This allocated memory storage is not available until garbage collector sweeps away the unused objects.To make any object unusable make the reference variable pointing to that object asnullpointer.In Java all the objects are garbage collected, when you make anullreference to the object. In Java you never explicitly free the memory allocated, instead the Java does automatic garbage collection. Example: public int GarMethod() { String s = new String("Test String"); System.out.println(s"); s = null; } |
In Java garbage collection is guaranteed only when the objects has null reference to it. The Java runtime system keeps track of the memory allocated and is able to determine whether the memory is still is usable or not. In the above example the object&aposs&aposis garbage collected by the Java Runtime System. But there is no guarantee that when the object is garbage collected. In Java, you can call System.gc() and Runtime.gc() methods , if you call these methods explicitly, the JVM makes efforts towards recycling the unused objects, but there is no guarantee that when the objects are garbage collected. In Java, it is a good idea to explicitly assignnullinto a variable when you have finished with it. Java does allow you to add a finalize() method to the class. The finalize() method will be called before the garbage collector sweeps away the object. In practice, we do not rely on the finalize() method for recycling any resources that are in short supply - you simply cannot know when this method will be called. Note:objects are garbage collected, not the references.
1. How can you force garbage collection?[a] Garbage collection cannot be forced [b] Call System.gc(). [c] Call Runtime.gc(). [d] Set all references to null. 2. Which statements about garbage collection are true?[a] The garbage collector runs in low memory situations [b] You can run the garbage collector when ever you want. [c] When it runs it releases the memory allocated by an object. [d] Garbage collector immediately runs when you set the references to null. 3. From the following code how many objects are garbage collected?String string1 ="Test"; String string2 ="Today"; string1 = null; string1 = string2; [a] 1 [b] 2 [c] 3 [d] 0
Answer 1[a] Garbage collection cannot be forced Answer 2 [a] The garbage collector runs in low memory situations [c] When it runs it releases the memory allocated by an object. Answer 3 [a] 1 |
受关注文章