Will it be garbage collection in the JVM?

I run the following code every two minutes through a timer:

object = new CustomObject(this); 

Potentially, it is a lot of created objects and many objects are rewritten. Do overwritten objects record garbage collection, even if the self-reference is used in a newly created object?

I am using JDK 1.6.0_13.

Thanks for the help.

+4
source share
4 answers

We need to know what is going on inside the constructor in order to fully answer the question.

But in the general case, while nothing retains a link to the old object when creating a new one, it will be available for garbage collection, even if the old object is used in the process of creating a new one.

For instance:

 class Foo { private String name; Foo() { this.name = null; } Foo(Foo f) { this.name = f.name; } public void setName(String n) { this.name = n; } public Foo spawn() { return new Foo(this); } } 

This will not save references to the old Foo when building the new Foo , so the old Foo may be GC'd:

 Foo f; f = new Foo(); // The first Foo f.setName("Bar"); while (/* some condition */) { // Periodically create new ones f = f.spawn(); } 

If Foo looked like this:

 class Foo { private Foo parent; Foo() { this.parent = null; } Foo(Foo f) { this.parent = f; } public Foo spawn() { return new Foo(this); } } 

... then each newly created Foo will refer to the previous Foo , and none of them will be available to GC.

+3
source

Java uses the mark and sweep garbage collector. This basically means: if it reaches your current code, it has no right to garbage collection, otherwise it is.

+2
source

It depends on what you do with the object in the constructor. If you store references to it in a newly created object, this will prevent the garbage collector from recovering memory.

The example below demonstrates this:

 class Inner { public Inner() { this.ref = null; } public Inner(Inner ref) { this.ref = ref; } Inner ref; } class Test { public static void main(String [] args) { Inner x = new Inner(); while(1==1) { x = new Inner(x); } } } 

In java, any available object from a living object will not be a candidate for garbage collection.

+1
source

There are no overwritten objects. object simply bound to a new instance of the object. While there are no additional references to a pre-existing instance, it is at some point deleted by GC. It doesn't matter if this child supports a parent link. Once it becomes unavailable, it will be marked for GC.

I assume this is not really java.lang.Object , what do you mean here.

0
source

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


All Articles