Based on the difference between stack and heap in Java the garbage collection mechanism in Java is introduced

  • 2020-04-01 01:37:59
  • OfStack

There are two types of memory in Java. They are called stack and heap, respectively.

The stack is the program memory space, so all references to primitive types and objects are stored in the stack.

Heap is where the Java virtual machine stores objects. It's a huge amount of memory. When you create an object, the Java virtual machine puts the object into the heap and the address of the created object into the stack.

Therefore, references to primitive types and objects are stored in the stack. The object is stored in the heap.

Garbage collection in Java

When you create a new object, Java allocates the required memory. When you run out of an object, the Java garbage collector collects the memory for you.

Garbage collection runs in the background as a thread, looking for objects that have no useful references, destroying them when found, and retrieving memory.

Garbage collection is implemented between Java virtual machines, and they usually follow the same steps, starting with the garbage collector taking a snapshot of the running threads and all the classes that have been loaded,

The objects involved in all the threads are then marked as recently used, and when all possible objects are marked, the unmarked ones are discarded.

To help the virtual machine, it is a good idea to actively remove objects that are no longer needed by setting the reference to null.

Eg:

Text t = new Test();

T.s omeAction ();

/ / all done

T = null;


Related articles: