Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 763
Suresh Atta Avatar asked Nov 27 '13 17:11

Suresh Atta


2 Answers

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.

like image 104
Trying Avatar answered Oct 22 '22 15:10

Trying


Not in general. Many JVM garbage collectors will move objects around, and the language makes no guarantees about the object's location.

There are some GCs (plain Mark&Sweep, for example) that do not; you can use a specialised JVM that supports these (such as a custom build of Jikes RVM) if you require this feature.

Note that each object can still contain a (mostly) unique ID (at least in the JVMs that I have seen), partly to support a basic implementation of hashcode.

like image 22
creichen Avatar answered Oct 22 '22 14:10

creichen