Garbage Collection

Mark-Sweep System Most implementation of Java language uses a mark-sweep garbage collection system.
Mark-sweep is a two phase process. The first pass, marks those objects that are no longer in use. Second pass is to remove (sweep) those objects from memory.
Object become eligible for deletion as soon as the last reference to them drops. If an object is in use the object is reachable. Unreachable objects are removed.
Marking object The mark phase starts with the root object, it looks to see if the object is already marked as in use. If it is marked, nothing happens. If it is not marked, the object is marked as in use. All objects that can be reached from the root are processed this way.
Sweep When the mark phase is complete, the sweep phase looks at each object in memory and looks if its marked. If it was, the seep phase clears the in-use flag and does nothing to the object. If the object is not marked, the object is freed and can be removed from memory.
Deletion actually occurs when free memory is exhausted, then garbage collection occurs.
Exam Tip Mark-sweep identifies unused objects, event if they refer to each other cyclically.
Exam Tip To detach an object from a program, set it to null. It has no reference.
Exam Tip Control of the deletion is out of the programmers hands.
Programmers can not tell when an object is about to be deleted or tell the garbage collector to delete the object.
protected void finalize() throws throwable To alert a programmer that an object is about to be deleted, the object’s finalize() method is called. It is a friendly warning from the JVM.
The finalize method is not required and is often omitted.
Exam Tip The finalize method is never call directly by programmer. The VM does it for you.
In the finalize() method, all user defined cleanup work can be performed. Make sure to call the super class finalize() method.
Calling finalize() methods is usually the first step in collecting objects.However, the JVM may not do this immediately.
Phantom objects are object whose finalize method were called but have not been collected.
System.runFinalization() Running System.runFinalization() request that the finalizer methods of objects be executed. No memory is however collected. System.runFinalization() really calls Runtime.runFinalization().
Exam Tip The order of object finalize() method are called are not guaranteed.
System.runFinalizeOnExit() A program may exit without calling the finalize() method. To make sure that the finalize method is called, the runFinalizeOnExit() method may be called.
Exam Tip Garbage collection runs until only the threads left are deaemon threads.
Controlling Garbage Collection Request of the runtime system can be made to carry out garbage collection. Suggest to carry out garbage collection.
The request can be ignored by the runtime system.
Exam Tip Garbage collection should be invoked before a time-critical section of code. Garbage collection take time, it is a good idea to request garbage collection before a time-critical code.
a: first = new String(“Hello”);b: first = null
Exam Tip The first place where the object referred to by first get’s collected is at label a. The String objects is derefenced at this point.Object referred to is what get’s collected, not the reference.
Garbage collection can be ran directly whenever needed.
Java provides routines to help control when garbage collection take place.
Runtime.gc() Request that garbage collection be carried out.
Heap Java manages memory in a structure called a heap.
Every object is created at the beginning of the application and managed automatically by Java.
Java insures that there is always memory on the heap by running garbage collection.
Java automatically works behind the scene to find objects that are not in use and automatically free them.
Java garbage collection can not give infinite memory.
Class Garbage Collection The JVM makes sure that unused objects are deleted from memory or collected.
Any object that eventually has no reference is considered unused and can be collected.
Exam Tip Java collects objects automatically. A program can not delete an object
Performance It take time to do garbage collection. The virtual machine stops when garbage collection thread is active.
Java runs only when memory is low. If there is enough memory the garbage will not run. When the request for memory find that there is not enough memory – garbage collection runs.
The collection of memory can happen at any time without notice or warning as long as the memory is low.
The JVM delays running garbage as long as possible. If there is enough memory, the unused objects are not deleted to free up memory.
The JVM goal is freeing up enough memory to satisfy an outstanding request.
If the VM can not free enough memory for the garbage collection request a java.lang.OutofMemoryError is thrown.
Managing Memory A request for garbage collection may be honored. There is no guarantee. The JVM does its best.
The total time garbage collection system takes compare to managing methods by hand is slightly more.
Hand written can work immediately, without waiting. However automatic memory management is guaranteed to run and try to free memory.
Runtime Class The runtime class is a singleton, a single object for each main program. It can not be instantiated. It is automatically created buy the JVM.
Runtime.getInstance() To get an instance of the Runtime object call Runtime.getInstance() method. It returns a singleton.
int Runtime.totalMemory() Returns the total amount of memory in bytes available for the JVM for allocating objects.
int freeMemory() Returns the total amount of free memory in bytes. This is less than the amount returned by totalMemory.
System Class The System class uses static methods to access the Runtime object instance.
System.gc() Calls the Runtime.gc(). This asks the method VM to perform garbage collection.
Exam Tip System.gc() or Runtime.gc() can not be relied upon to free up enough memory, or actually get the garbage collection to run.
Memory Management References Java 2 platform augmented the original Java memory management model with reference classes.
They defin the quality of control on an object reference
Reference Class Reference classes use more sophisticated memory management.
Reference now has two meaning:

  • The original meant how objects refer to each other using the new So long a the object has reference it will not be collected. In generic term reference means: “a way that one objects refers to, keeps track of, points to, or uses another object.”
  • In the new usage, reference is the name of a class (Reference) used in advanced memory management. They are closely related.
The Reference class is never instantiated, it is an abstract class.
WeakReference, SoftReference, and PhantomReference The Reference class is the superclass for: WeakReference, SoftReference, and PhantomReference class.
Exam Tip All these classes are predefined and cannot be created and instantiated.
Object Life Cycle These new classes give greater control over the life cycle of an object.
They are external representation of garbage collector internals.
We are given a garbage collector hints on how we are using objects in our application.
Strong Reference By default, programmers work with strong references. Strong reference are used to prevent objects from being garbage collected. It is a reachable object.
There is no Strong reference class. But is the idea of normal used references when the new operator is used.
Exam Tip They provide a degree of successively less control over the life cycle of the object.
Strong references tell the garbage collector that the referred-to object will not go away as long as the referring object is alive.
Exam Tip Cache A soft references tell the garbage collector that the referred-to object can go but you’d rather it did not. Put is in statis – we might resuscitate.
Exam Tip A weak references tell the garbage collector that you don’t care if the referred-to object goes away, you just want to know about it. Logs its death.
Exam Tip A phantom reference tells the garbage collector to run finalize method for the referenced object, but that the memory should not be reused until you release it.
Shared Interface The Reference class has a few methods.
clear(), enquee(), isEnqueued() and the get() method.The get() method is what will be used most often.
referent get() It returns the object the reference referred-to.As long as it has not been collected. This object is know as the referent.
Or, it returns null if it has been collected. Then the reference is no longer valid.
get() returns an Object which should be casted to the correct class.
clear() Sets the reference to null. This forces get() to return null.
enqueue() Adds the reference to the reference queue that the reference is associated .
isEnqueued() Returns true if the reference has been added to the queue.
The method description are generic methods and are affected by the protocol of the reference object Reference class.
Soft Reference Soft references can be used to create memory sensitive cache.
Memory sensitive cache are usually operations which result in before and after state that can be reversed. Before changes and after changes can be swaped. This is a feature of undo feature.
Soft reference tells the runtime system that we would rather this object not be removed from memory.
We don’t require that the object not be removed, but rather it not be. A reference to the object maybe maintained.
Inactive before or after image can be stored as a SoftReference.
SoftReference inactiveImage;inactiveImage = new SoftReference( activeImage, null );
The first argument is the object we want to maintain a soft reference., The second is the reference queue associated with this reference.
Restoring the object means transforming the referenced object back to a strong object:
activeImage = transformation.transform( activeImage );inUndoState = false;
At this point there is strong reference to the new active image (the transformed image) and a soft reference to the old active image, the before image.
If the garbage collection runs, since we have a soft reference to the before image, the garbage collection will try to free up memory without touching the softly-referenced object. It will try to leave it alone.
If come to push, the garbage collection will delete this soft-refenced object. It is memory sensitive.
The SoftReference has a get() method that can be use to obtain a strong reference to the object that the soft reference manages.
SoftReference newInactive = new SoftReference( activeImage, null );activeImage = (Image) inactiveImage.get();

inactiveImage = newInactive;

If the object gets collected, the get() method returns null.
SoftRefence may keep the object around.
Exam Tip A SoftReference is eligible for collection until the strong reference is dropped. Usually after the SoftReference constructor has assigned the object.
Weak Reference Watching someone else’s object. Weak references are similar to soft reference in that they allow you to refer to an object without forcing the object to remain in memory.
Garbage collection does not have to keep the memory.
Best used to keep track of object that someone else owns.
You just want to know if the object is in memory.
WeakRefence objects are not kept around. They disappear more quickly.
Weak reference use reference queue.
Exam Tip A weak reference allows an object to be tracked, but does not prevent that object from being collected.
Exam Tip A weak reference does not allows an object to be tracked after it is collected.
Reference Queue Tells when reference queue change. When soft and weak reference become null.
In additional to going null, soft and weak reference are added to a reference queue.
The reference queue gives you a means for determining in bulk which references have changed.
It is a quick means of determining which of the references you created have changed. the get() method does not have to be tested.
A reference queue can be supplied as a second argument, an reference constructor.
Reference give the JVM a mechanism for telling you that it has collected an object and that the reference has moved to an invalid state.
enqueue() When a soft reference is collected, it is added to the reference queue – enqueuing.
Checking to see if the reference has been added to the queue will tell a programmer that the object is not available.
We can also use the get() method to see if the method returns null.
Reference queues can be used by creating different threads to monitor threads added to the queue.
The call of the ReferenceQueue class methods can be polled for access.
poll() Returns a reference in there is one in the queue, or null otherwise.
remove() Returns null if there is no reference in the queue, but will return the reference and remove it from queue if there is.
It will wait forever until a reference is added to the queue.
remove( long timeout ) Provides a timeout for the process.
When soft or weak reference are added to a reference queue, they are automatically cleared.
The reference will become null, and added at the same time to the queue.
There will never be a reference in the queue that will not return a null from the get() method.
Phantom references are not automatically cleared.
Phantom References Phantom reference delay the reuse of memory occupied by an object. Even if the object itself is finalized.
A phantom is an object that has been finalized, but whose memory has not yet been made available for another object (collected).
Phantom reference track memory rather than objects. This is different than Soft or Weak References.
Exam Tip A phantom reference object can never be reached.A phantom reference object has no referent object.
The memory of a phantom reference is monitored.
There are two reason memory release is delayed, because of performance and native code.
Native code may need to drop the memory reference before completing its task.
When the garbage collector determines that the object is only reachable through phantom references, it will finalize the object and add it to the reference queue.
The memory is not collected until the clear() method on the reference is called.
For phantom references the queue has to be polled to remove the references by calling clear() method. It is not done automatically.
Soft and Weak references are automatically cleared.
Phantom references get() always return null.
Exam Tip Phantom reference prevent memory from being reused.
Exam Tip Reference queues are required for Phantom references. Because phantom references always return null, The reference queue is used to determine if they are invalid.
Reference Strength References are ordered as: strong, soft, weak or phantom references.
Objects are then known as: strong reachable, softly reachable, weak reachable or phantom reachable, or unreacheable.
Strongly Reachable If an object has strong, soft, weak or phantom references pointing to it, than the object is considered strongly reachable and will not be collected.
Softly Reachable If an object has soft, weak or phantom references pointing to it, than the object is considered softly reachable and will be collected when memory gets low.
Weakly reachable If an object has weak or phantom references pointing to it, than the object is considered weakly reachable and will be collected at the next garbage collection cycle.
Phantom reachable If an object has phantom references pointing to it, than the object is considered phantom reachable and will have tis finalized method calls, but the memory of that object will not be collected.
Unreachable If an object has no strong, soft, weak or phantom references pointing to it, than the object is considered unreachable and has already been collected, or will be collected at the next garbage collection cycle.
Exam Tip Referent objects are created only for soft and weak objects. These are returned by the get() method.