Time to question JAVA System.GC() and System.runFinilizer
public interface SomeAction {
public void doAction();
}
public class SomePublisher {
private List<SomeAction> actions = new ArrayList<SomeAction>();
public void subscribe(SomeSubscriber subscriber) {
actions.add(subscriber.getAction());
}
}
public class SomeSubscriber {
public static int Count;
public SomeSubscriber(SomePublisher publisher) {
publisher.subscribe(this);
}
public SomeAction getAction() {
final SomeSubscriber me = this;
class Action implements SomeAction {
@Override
public void doAction() {
me.doSomething();
}
}
return new Action();
}
@Override
protected void finalize() throws Throwable {
SomeSubscriber.Count++;
}
private void doSomething() {
// TODO: something
}
}
Now I'm trying to force GC and Finalizer within main block.
SomePublisher publisher = new SomePublisher();
for (int i = 0; i < 10; i++) {
SomeSubscriber subscriber = new SomeSubscriber(publisher);
subscriber = null;
}
System.gc();
System.runFinalization();
System.out. println("The answer is: " + SomeSubscriber.Count);
Since JAVA GC call is not guaranteed to be called (as explained on javadoc and Since JAVA GC call is not guaranteed to be called (as explained on javadoc and When is the finalize() method called in Java?,
my init thought was that it would out put random SomeSubscriber.Count. (At least '1' as force by System.GC and finalizer.)
Instead it's always 0.
Can anyone explain this behavior?
(plus, does static member field exists independant of class instances and never be destroyed during code execution?)