Question

I have a Java SE application with CDI/Weld (started with org.jboss.weld.environment.se.StartMain, without any application server). What is the proper way to start a background service inside it?

I've tried creating a @Singleton bean which observes the ContainerInitialized event (like below) but I'm not sure when the container will destroy this service bean. Is it safe? Is there a better way?

@Singleton
public class BackgroundService {

    public void onStart(@Observes ContainerInitialized event) {
        // starting other threads etc.
    }
}
Was it helpful?

Solution

I personally would use @ApplicationScoped not @Singleton. The lifecycle will shutdown the object when the container shuts down. If you want to start a thread, this would be a likely choice to put the code.

It is not asynchronous by default, so you'll need to start the thread yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top