1

I have a class that has a static reference to Spring's ApplicationContext. I need to clear that context and run destroy method of its singleton beans when the class is about to be unloaded. So, is there some class level finalizer callback that is called when the class is unloaded, so I can clear the context in that callback?

I have a vague idea of using WeakReferenceQueue and a counter to keep track of un-referenced objects of that class so I can detect when the class has no live objects, but that still won't tell me when the class itself is unloaded.

shrini1000
  • 7,038
  • 12
  • 59
  • 99
  • 5
    This is the sort of work that you should let the container worry about and handle. Objects that have to deal with their own lifecycle are code smells and very difficult to implement 100% correctly. – Matt Ball Aug 15 '12 at 04:22
  • All classes effectively have a strong reference to their class loader which in turn has strong references to all its classes. So all the classes for a single class loader become collectible together. – Tom Hawtin - tackline Aug 15 '12 at 04:43

2 Answers2

1

The way to "unload a class" is to have all classes unreachables and the ClassLoader that loaded them too. See Unloading classes in java? for a complete explanation of this process.

A Class is an object like any other in Java. So the classic call to finalizer() is implemented for classes too. This method is called by the Garbage Collector, not you explicitly.

There are no other standard way to unload classes or objects in Java. You can do it by yourself by implementing a method (say "dispose()" for example) that could do some actions if no other object references the object containing dispose() (known as "RefCount").

To know the current refcount of an object or really force garbage collection, you've got to use JVM Tool Interface.

You could also try to call System.runFinalization() but no guarantee is given by the JVM that all finalizers will be called.

Community
  • 1
  • 1
Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
  • I'm aware of how classes get unloaded. My question is about if there's some class level callback method provided by Java, which is called when a class is about to be unloaded. If not, is it possible to simulate that and if yes, how? – shrini1000 Aug 15 '12 at 05:59
1

So, is there some class level finalizer callback that is called when the class is unloaded.

I looked in the obvious places and as far as I can tell, there isn't such a callback. And I can't think of a way to implement one, apart from hacking the JVM itself.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216