Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do instance methods strongly reference their objects?

Does myObject::someMethod strongly reference myObject? For some background, consider these two classes:

class TakesRunnable {
    private Runnable runner;

    TakesRunnable(Runnable runner) {
        this.runner = runner;
    }

    public void run() {
        runner.run();
    }
}

class Foo {
    public void runMe() {
        ...
    }
}

If I were to instantiate a Foo object, create new TakesRunnable(foo::runMe), and then lose my local reference to foo, would foo be garbage-collected underneath me or would my TakesRunnable object maintain a strong reference to it? I would imagine the latter but that’s because I spend a lot of time in Python.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, instance-method references maintain a reference to the object they relate to.

So in your case, the object foo will remain uncollectable until that method reference goes out of scope.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading