4

I was going through finalizer guardian example posted on Stack Overflow, I have few questions regarding this:

  1. Why do we need to create a Guardian object? Why won't simply overriding the finalizer work? (as all classes are subclasses of the Object class).

  2. At what moment is the Guardian object created? I assume that it is during class loading.

  3. I didn't understand syntax of guardian object being created. A function is declared along with variable declaration. What this paradigm is called in Java?

Community
  • 1
  • 1
user1743514
  • 311
  • 1
  • 3
  • 21

1 Answers1

4
  1. Correctly overriding finalize() will of course work. I believe the guardian trick is to make sure that, even your overridden finalize() is not calling super.finalize(), guardian is invoking the parent's finalizer before your child class's finalizer.

  2. When the enclosing object instance is created. The guardian object is nothing but an instance variable

  3. That is anonymous (inner) class. I believe this is covered in most Java books or tutorials. Try to Google with "java anonymous class" will give you quite a lot of resources, for example, http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • +1, but I'd add a either bit more explanation to 3., or at least a link - as the OP would seem to benefit from that. – ppeterka Jan 07 '13 at 08:18
  • Well, I though this is covered in almost all beginner book for Java. Anyway I am adding one link that I find by google. – Adrian Shum Jan 07 '13 at 08:34
  • @AdrianShum, So basically the guardian trick is is simply for **solving security issues** with code that refuse to play nice? – Pacerier Sep 17 '17 at 22:26