Announcement Announcement Module
Collapse
No announcement yet.
@Configurable bean doesn't get 'unregistered'? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Configurable bean doesn't get 'unregistered'?

    I have an external component that is autowired using the AspectJ @Configurable weaving because I need one instance per session and its from an external framework.

    I was interested in counting objects instances to ensure that spring was able to take on and then give up the object, so I put together the below code. As I create instances the instanceCount goes up, however when I destroy the bean (by setting to null) the instance count doesn't drop.

    What's going on here? Is the garbage collector needed to clean up the object (and does this interact with the container!)? Or is there a specific way to unregister from Spring in order to run the @PreDestroy method?

    Thanks,

    David

    Code:
    @Configurable
    public class MyBean extends ExternalFrameworkObject {
    
        @Autowired
        private Dependency dependency;
    
        private static int instanceCount = 0;
        private static final Object countLock = new Object();
    
        @PostConstruct
        public synchronized void init() {
            synchronized (countLock) {
                System.out.println(++instanceCount + " instances on heap");
            }
        }
    
        @PreDestroy
        public synchronized void destroy() {
            synchronized (countLock) {
                System.out.println(--instanceCount + " instances on heap");
            }
        }
    }

  • #2
    Basically that is terrible way to count object instances (you should use a profiler). The @PreDestroy method is called by the container when the object gets destroyed, simply setting a reference to the object to null isn't going to tell the container that it needs to be destroyed... setting reference to null != destroying the bean.

    Is the garbage collector needed to clean up the object (and does this interact with the container!)?
    As you noticed it doesn't interact with the container.

    Or is there a specific way to unregister from Spring in order to run the @PreDestroy method?
    By calling it manually, spring doesn't know about the beans you create yourself (even if they are @Configurable) so that also means YOU are in control of the bean lifecycle and not the spring container.

    Although a bad way to get this working is to implement the finalize method and call the destroy method. Also instead of using synchronized methods and synchronized blocks (not sure why you use both?!) use an AtomicInteger with the appropriate methods.

    Comment

    Working...
    X