Sambit
Sambit

Reputation: 8011

How to start a thread inside spring container

Please help to resolve a problem. I have a thread like below the code.

public class A implements Runnable {

  public void run() {
     while(true) {
     //Do something something important
    }
  }

}

I want to configure this thread in spring configuration file in such a manner, so that when spring container gets started, the thread start running. It means I have to start the thread using th.start() in a class, but that will never be used. The thread should start without instantiating any bean from the container. It is not Timer task type functionality.

Upvotes: 2

Views: 2920

Answers (2)

suhas_n
suhas_n

Reputation: 147

create one class which implements ApplicationListener and wire your thread start logic on oeverridden method of it .

Example :

            public class A implements Runnable {

                  public void run() {
                     while(true) {
                     //Do something something important
                    }
                  }

            }
                  public class B implements ApplicationListener<ContextRefreshedEvent> {

                      @Override
                        public void onApplicationEvent(ContextRefreshedEvent event) {
                            Thread t = new Thread(new A());
                            t1.start()

                      }

                  }

Upvotes: 0

Steve McKay
Steve McKay

Reputation: 2223

<bean class="java.lang.Thread" init-method="start">
    <constructor-arg index="0">
        <bean class="A"/>
    </constructor-arg>
</bean>

This will create and start a thread, making the thread a bean. You could maybe use destroy-method="interrupt" to stop the thread when the container stops, but anything fancier would require support code. I recommend Guava's AbstractExecutionThreadService for that.

Upvotes: 2

Related Questions