How do I initialize and destroy beans in Spring?

When creating an instance of a bean you might need to do some initialization to the bean. Likewise, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean.

To do this initialization and destroy routine you can use the init-method and destroy-method attribute when declaring a bean in spring configuration using the <bean> element.

By defining the init-method and destroy-method it will allow the Spring Container to call the initialization method right after the bean created. And just before the bean removed and discarded from the container, the defined destroy method will be called. Let’s see some code snippet as an example.

package org.kodejava.spring.core;

public class AutoEngine {
    public void initialize() {
        System.out.println("AutoEngine.initialize");
    }

    public void destroy() {
        System.out.println("AutoEngine.destroy");
    }
}

Below is the Spring configuration file that where we register the bean. You’ll see in the configuration there are additional attributes that we add to the bean.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="engine" class="org.kodejava.spring.core.AutoEngine" init-method="initialize" destroy-method="destroy" />

</beans>

Create a small program to execute our demo:

package org.kodejava.spring.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("init-destroy.xml");

        AutoEngine engine = (AutoEngine) context.getBean("engine");

        // context.close will remove the bean from the container. 
        // This will call our bean destroy method.
        context.close();
    }
}

When you run the program it will print the following output:

AutoEngine.initialize
AutoEngine.destroy

The advantage of using this method to initialize or clean up the bean is that it does not mandate our bean to implement or extend any Spring API which will make our bean reusable on other container beside Spring.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I check whether a thread group has been destroyed?

You can use ThreadGroup.isDestroyed() method to check whether a thread group and its subgroups has been destroyed.

package org.kodejava.lang;

public class CheckGroupDestroy {
    public static void main(String[] args) {
        ThreadGroup grandParent = new ThreadGroup("GrandParent");
        ThreadGroup uncle = new ThreadGroup(grandParent, "Uncle");
        ThreadGroup parent = new ThreadGroup(grandParent, "Parent");
        ThreadGroup son = new ThreadGroup(parent, "Son");
        ThreadGroup daughter = new ThreadGroup(parent, "Daughter");
        ThreadGroup neighbour = new ThreadGroup("Neighbour");

        ThreadGroup[] groupArray = {
                grandParent, uncle, parent, son, daughter, neighbour
        };

        // Destroy 'parent' group and all its subgroups
        parent.destroy();

        // Check whether the group is destroyed. The result is,
        // GrandParent, Uncle, and Neighbour did not destroyed
        // because they are not Parent's subgroups
        for (ThreadGroup tg : groupArray) {
            if (tg.isDestroyed()) {
                System.out.println(tg.getName() + " is destroyed");
            } else {
                System.out.println(tg.getName() + " is not destroyed");
            }
        }
    }
}

The result is:

GrandParent is not destroyed
Uncle is not destroyed
Parent is destroyed
Son is destroyed
Daughter is destroyed
Neighbour is not destroyed

How do I destroy a thread group?

You can destroy a thread group by using destroy() method of ThreadGroup class. It will cleans up the thread group and removes it from the thread group hierarchy. It’s not only destroy the thread group, but also all its subgroups.

The destroy() method is of limited use: it can only be called if there are no threads presently in the thread group.

package org.kodejava.lang;

public class ThreadGroupDestroy {
    public static void main(String[] args) {
        ThreadGroup root = new ThreadGroup("Root");
        ThreadGroup server = new ThreadGroup(root, "ServerGroup");
        ThreadGroup client = new ThreadGroup(root, "ClientGroup");

        // Destroy 'root' thread groups and all its subgroup
        // ('server' & 'client')
        root.destroy();

        // Check if 'root' group and its subgroups already destroyed
        if (root.isDestroyed()) {
            System.out.println("Root group is destroyed");
        }

        if (server.isDestroyed()) {
            System.out.println("Server group is destroyed");
        }

        if (client.isDestroyed()) {
            System.out.println("Client group is destroyed");
        }
    }
}