Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can’t force it.
What is an unreachable object? An object’s life has no meaning unless something has reference to it. If you can’t reach it then you can’t ask it to do anything. Then the object becomes unreachable and the garbage collector will figure it out. Java automatically collects all the unreachable objects periodically and releases the memory consumed by those unreachable objects to be used by the future reachable objects.
We can use the following options with the Java command to enable tracing for garbage collection events.
-verbose:gc reports on each garbage collection event.
Explain types of references in Java? java.lang.ref package can be used to declare soft, weak and phantom references.
Garbage Collector won’t remove a strong reference.
- A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks.
- A weak reference will get removed on the next garbage collection cycle. Can be used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references.
- A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.
No comments:
Post a Comment