Java finalizer and gc

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 am trying to force GC and Finalizer in the 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 a JAVA GC call is not guaranteed to be called (as explained in javadoc and since a JAVA GC call is not guaranteed to be called (as explained in javadoc and When () called in Java? Ends ,

my initial thought was that it would output random SomeSubscriber.Count. (At least '1' as a force for System.GC and the finalizer.)

Instead, always 0.

Can anyone explain this behavior?

(plus, does a static member field exist independent of class instances and will never be destroyed at runtime?)

+4
1

- , System.gc() System.runFinalization() GC , , .

10 :

SomeSubscriber subscriber = new SomeSubscriber(publisher);

SomeSubscriber, :

publisher.subscribe(this);

, , . ?

actions.add(subscriber.getAction());

, getAction() . getAction()?

public SomeAction getAction() {
    final SomeSubscriber me = this;
    class Action implements SomeAction {

        @Override
        public void doAction() {
           me.doSomething();
        }
    }

    return new Action();
}

. SomeSubscriber. , - me , . - !

, publisher, . System.gc() System.runFinalization(), publisher , , SomeSubscriber .

, publisher = null, , , . Count volatile ( Count, Count - ), .

+2

Source: https://habr.com/ru/post/1622006/


All Articles