Java Assignment Memory Leaks

I must assume that the following method does not leak memory:

public final void setData(final Integer p_iData) { data = p_iData; } 

Where data is a property of some class.

Each time the method is called, a new Integer replaces the existing data link. So what happens to current / old data?

Java should do something under the hood; otherwise, we would need to reset any objects every time the object is assigned.

+6
source share
7 answers

Simplified explanation:

Periodically, the garbage collector looks at all the objects in the system and sees that they are no longer available from live links. It frees up any objects that are no longer available.

Note that your method does not create a new Integer object at all. A reference to the same Integer object can be transmitted, for example, again and again.

The reality of garbage collection is much more complicated than this:

  • Modern GCs tend to be generational, suggesting that most objects are short-lived, so you don't need to frequently check the entire (possibly large) heap; he can just often check "recent" objects for life
  • Objects can have a finalizer - code that must be run before garbage collection. This delays the collection of garbage from such objects in a loop, and the object can even β€œresurrect” itself, making itself available
  • Modern GCs can be built in parallel and have many settings
+7
source

Java is a garbage collected language.

When there are no longer links to live links to an object, it becomes suitable for garbage collection. The collector from time to time starts and restores the memory of the object.

In short, your code is 100% correct and not a memory leak.

+3
source

The result is garbage.

0
source

if there is no link to data , the java garbage collector will clear old data and free up memory

0
source

Actually, since Integer is not an object of a primitive type, the line:

 data = p_iData; 

updates the link.

Now the old object that this.data used to indicate will be checked by the GC to determine if there are any more references to this object. If not, this object is destroyed and memory is freed (later)

0
source

If an object previously referencing data no longer refers to any structure of the object referenced by any working thread, it has the right to a garbage collector. GC runs Java in the background to free up memory on unused objects.

0
source

I want to show you one example in some code:

 int x; x=10; x=20; 

I initially assigned x to 10 again x to 20 the first reference memory will be processed by Java GC. The Java GC is a thread that runs continuously and checks for raw memory and cleans it.

0
source

Source: https://habr.com/ru/post/898613/


All Articles