2

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.

Sambit
  • 7,625
  • 7
  • 34
  • 65
  • Put this under @PostConstruct follow the [LINK][1] for details [1]: http://stackoverflow.com/questions/2401489/execute-method-on-startup-in-spring – LynAs Mar 02 '15 at 18:45

2 Answers2

2
<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.

Steve McKay
  • 2,123
  • 17
  • 26
0

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()

                      }

                  }
suhas_n
  • 147
  • 2
  • 2
  • 11