2

From what I understand , if Object A has a reference to Object B as its instance variable , then the reference is stored within the space allocated for Object A on the heap. But Object B itself is stored somewhere else on the heap , outside of space allocated for Object A.

Is this understanding accurate ? What are the advantages of doing memory allocation this way (as opposed to having Object B within Object A on the heap) ?

What are the impacts of this (positive or negative) on the performance of Java's garbage collection mechanism (i.e if Object A get destroyed)?

2
  • 3
    Imagine two different objects had references to object B. How would you represent that in your proposed scheme? Commented Jul 24, 2015 at 16:03
  • i see. it makes sense the way jvm does mem allocation for Object B. Commented Jul 24, 2015 at 16:07

3 Answers 3

2

One of the major benefits is independence of the objects - if B was allocated within A, B could only be collected when A was collected.

As separate objects on the heap, B can now be passed and referenced elsewhere, independently of A, and B will have a lifespan of its own.

The Garbage Collector will know when there are no further root references to either object - e.g. even if A is collected, there might still be other references to B which will prolong its lifespan.

Sign up to request clarification or add additional context in comments.

Comments

0

Bs instances might also be created independently, or they could be used as instance fields for other objects, e.g. Object C. If you had instances of B within A or C, you would need to "copy" Bs around, or let C refer A to get B (clearly not a good idea).

So objects have their own allocation space and, when they need to refer to specific instance of other objects, they just store a "pointer" to their location instead.

Also, following your example, if you have the following code:

class A {
    private B myB = new B();

    public B getB() { return this.myB; }
}

and some code, say from Object C, calls B myB = myA.getB();, then you would not want to tie C's instance to A's. If A gets GC'd C can still keep its B just fine. This is because B is not coupled (memory-wise) to A or anything else.

Finally, and related to the last point, remember that GC is based on an object graph, and only unreachable nodes are collected. This is simplified greatly by As, Bs and Cs being independent nodes (vertexes) and their references the connecting arrows (edges) in the graph.

Comments

0

What you propose ("Objects" baked in the memory of their parent object) will be covered by value types. See also http://openjdk.java.net/jeps/169

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.