Garbage Collection

 When an object is created, memory will be allocated in the heap. Heap is memory pool which is accessible for whole application. If memory is not available, JVM does garbage collection so as to allocate memory for the object. Otherwise JVM  generates OutOfMemoryError and quits.

Heap is split into different sections called generations. When an object is created, it is allocated in the Eden Space.  If it survives garbage collection, it will be promoted to Survivor Space. If it live long, it will be allocated to Tenured Generation where the garbage collection is less frequent. The fourth is PermGen or Permanent Generation, where objects are not eligible for garbage collection.In java8 this is replaced with Metaspace.

Garbage collection is the mechanism of retrieving the memory which is already allocated to an object and no longer needed, so that it can be reused. In languages like C/C++, memory has to be allocated and and has to be freed. But in languages like JAVA and C# , garbage collection is automated.

Garbage collection in java is called mark and sweep. A low priority thread is allocated for garbage collection. Garbage collector does stack walk and marks the objects in the heap that are used. And in the heap it removes the unmarked one and frees the memory.

Comments

Popular posts from this blog

Transform values with a stream

Collections Framework

Inspect a collection