What happens to dangling pointers in java?

What happens to dangling pointers in java?

What happens to dangling pointers in Java? Supposedly there is garbage collection, but when is it performed? From what Ihave read, it seems really easy to have persistent danglingpointers (pointers to objects that no one is using that aren’t being cleaned up by garbage collection).

Let’s say I have a collection of objects, and one of the functions that manipulates the collection is called removeObject(int i), which removes the ith object from the collection and returns a pointer to the removed object.

Sometimes I need to get the removed object to salvage it for reuse; other times I simply want to remove the object. Is the returned pointer left dangling if I don’t assign it when I make the function call? Should it be left to the function-caller to dispose of unused objects, or should the programmer maketwo functions, deleteObject() and removeObject()?

By definition, a dangling reference is an active binding between aname and a de-allocated segment of the heap. By definition, garbageis a segment of the heap that is no longer bound to a name by anactive binding. Only garbage is de-allocated by the garbage collector;hence, a dangling reference is not possible. This, and no memoryleaks, are the principle advantages of garbage collection.

If I understand your example, you are asking what the difference is between

x = removeObject(i);
Assuming there are no other active references to the i-th objectof the collection, this object becomes garbage after the firstcall. A pointer to the object was returned, but was not bound toa name, hence there is no dangling reference.

By contrast, the returned pointer was bound to x in the second call, so it can still be accessed through the name x, and is not garbage.

See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist