General question
In Java, there is no reference pointing to an object, but one of the methods of this object is still on the call stack.
Is it possible that the garbage collector removes this object before its method is popped off the call stack, or does it wait until the method is popped off?
(please refer to my specific problem below)
Specific problem
Class structure
Implementation of a simple singly linked list:
- class LIST: attribute "begin" of type LIST_ELEMENT
- abstract class LIST_ELEMENT with all needed abstract methods
- the classes END and NODE inherit from LIST_ELEMENT
- END does not have any attributes, it always marks the end of the list
- the attributes of NODE are "next" of type LIST_ELEMENT and "data" of type DATA_ELEMENT
- DATA_ELEMENT is an interface which has to be implemented by any class that is to be stored in the list
Methods of LIST
- insertSorted: inserts an element while keeping a sorted list sorted
- sort: sorts the list by first clearing the list and then by using the method insertSorted to insert each element again
Code
public class LIST
{
private LIST_ELEMENT begin = new END();
// some methods to add or remove elements
public void clear()
{
begin = new END();
}
public void insertSorted(DATA_ELEMENT dataNew)
{
begin = begin.insertSorted(dataNew);
}
public void sort()
{
begin.sort(this);
}
}
public abstract class LIST_ELEMENT
{
public abstract LIST_ELEMENT insertSorted(DATA_ELEMENT dataNew);
public abstract void sort(LIST list);
}
public class END extends LIST_ELEMENT
{
@Override
public LIST_ELEMENT insertSorted(DATA_ELEMENT dataNew)
{
return new NODE(this, dataNew);
}
@Override
public void sort(LIST list)
{
list.clear();
}
}
public class NODE extends LIST_ELEMENT
{
private LIST_ELEMENT next;
private DATA_ELEMENT data;
public NODE(LIST_ELEMENT nextNew, DATA_ELEMENT dataNew)
{
next = nextNew;
data = dataNew;
}
@Override
public LIST_ELEMENT insertSorted(DATA_ELEMENT dataNew)
{
if(data.isSmallerThan(dataNew))
{
next = next.insertSorted(dataNew);
return this;
}
else
{
return new NODE(this, dataNew);
}
}
@Override
public void sort(LIST list)
{
next.sort(list);
list.insertSorted(data);
}
}
public interface DATA_ELEMENT
{
public boolean isSmallerThan(DATA_ELEMENT dataCompare);
}
Question
Having implemented this sorting algorithm, is it safe?
Can the garbage collector remove the data from the NODE objects after the list was cleared (so the call
list.insertSorted(data);
does something unexpected), or does the method on the call stack count as a reference to the object so that the data attribute is valid for the entire duration of the call of LIST.sort?
Is it guaranteed that the object is not removed during this time?
In my testing, the call to LIST.sort always sorted the list as expected.