Will local variables declared in a Java function be automatically freed?

If a variable is declared inside a function in Java, will this variable be automatically freed upon completion of this function, regardless of its type? Will the memory occupied by the primitive type be non-primitive Objectand / or a arrayeither primitives, or Objectsafter this scope has been freed?

+4
source share
3 answers

Primitive types in Java are allocated on the stack, so their memory is automatically freed when they go out of scope. Object references are primitives that are similarly managed, but the objects themselves collect garbage. They will be automatically deleted by the garbage collector, but it is not guaranteed how long it will take.

The JVM garbage collector starts automatically when the pressure in the memory becomes hard, so as long as there is no reference to the object, you can effectively make the assumption that its memory will be freed.

+7
source

If there is no reference to the object, the garbage collector will automatically delete it. But we cannot say when this will happen.

This article has a pretty good explanation of how the garbage collector works.

0

Allexis King Answer

There is another method in the new Java / JVM that decides whether a local object should be allocated in Stack or Heap. local objects allocated on the stack by this technology will be de-distributed upon exiting the scope

Escape Analysis

Escape Analysis is a method by which the Java Hotspot Server compiler can analyze the scope of a new object and decide whether to allocate it to a bunch of Java.

Escape analysis is supported and enabled by default in Java SE 6u23 and later.

0
source

All Articles