Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

java - Is the address of an object fixed during its life cycle?

Is the address of an object constant during its life cycle or can it change? I just thought address of an object never changes. Is it JVM dependent? I Haven't found any clear spec.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The address of an object in java is not fixed; rather, it may change (subjected to conditions).

This is because normally objects are allocated in eden space. Then they move to survivor space, then also to the old generation space if they survived some garbage collection cycles. So it does change. But if the object is allocated in eden space and also garbage collected by staying in the same space, then the address will not change. Similarly if the object is too large to be allocated in eden space, then the JVM allocates the object in the old generation and if it is garbage collected by staying where it was allocated, then also address does not change.

One more thing you should know that even if one object stays in a generation, if it is garbage collected by staying in the same generation, the address may change, because it may have moved by the garbage collector while doing garbage collection, e.g. from eden space to survivor, survivor to survivor or even into the old generation in the event of compacting.

From the above conditions it is clear that the moving of an address is JVM dependent.

Hope it helps.

EDIT

Answering the below question:

if I create a new Object and store it in a map, where it is stored based on hashCode (which is generated using the object's memory location as per java). Now the address of the object changed(resulting in a different hashCode), so as per the answer, the code can never fetch the object from the map??

hashCodes are saved in the object header by JVM. So it is constant. While creating an object it is assigned to 1 by default but when you use the object for the first time it gets calculated and gets stored in the header. It never changes throughout the life of the Object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...