How can I run initialization code in the background on server startup
sg26565 Aug 22, 2011 3:09 PMHi,
I'd like to run some initialization code when AS 7.0.1 starts up. However, I don't want to block the startup of the server. Therefore, I'm trying to run the code in the background.
So far, none of the options worked for me:
1) I wrote a signleton session bean with @Startup @Sigleton and a @PostConstruct method that calls an @Asynchronous method:
@Startup
@Singleton
public class StartupSingleton {
@Inject
private Logger logger;
@Asynchronous
private void asyncInit() {
logger.info("begin initialization");
try {
Thread.sleep(3000L);
} catch (final InterruptedException e) {
}
logger.info("done initialization");
}
@PostConstruct
public void Start() {
logger.info("call asyncInit()");
asyncInit();
logger.info("continue startup");
}
}
Expected result is:
call asyncInit() begin initialization continue startup ... done initialization
... but instead I get:
call asyncInit() begin initialization ... done initialization continue startup
2) I moved the @Asynchronous method to a separate @Stateless session ejb and @Injected it onto the @Singleton
@Startup
@Singleton
public class StartupSingleton {
@Inject
private Logger logger;
@Inject
private InitBean bean;
@PostConstruct
public void Start() {
logger.info("call asyncInit()");
bean.asyncInit();
logger.info("continue startup");
}
}
@Stateless
public class InitBean {
@Inject
private Logger logger;
@Asynchronous
public void asyncInit() {
logger.info("begin initialization");
try {
Thread.sleep(3000L);
} catch (final InterruptedException e) {
}
logger.info("done initialization");
}
}
3) Fired a ContainerStartupEvent and @Observe it in a separate class:
@Startup
@Singleton
public class StartupSingleton {
@Inject
private Logger logger;
@Inject
private Event<ContainerStartupEvent> event;
@PostConstruct
public void Start() {
logger.info("fire event");
event.fire(new ContainerStartupEvent());
logger.info("continue startup");
}
}
public class StartUpObserver {
@Inject
private Logger logger;
public void startup(@Observes final ContainerStartupEvent event) {
logger.info("begin initialization");
try {
Thread.sleep(3000L);
} catch (final InterruptedException e) {
}
logger.info("done initialization");
}
}
4) Manually creating a new thread insde the initialization code doesn't work either, because then injected beans are not accessible on the new thread.
Is there another solution to run code on server startup asynchronously?