jt8
jt8

Reputation: 25

Background service with CDI

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

Upvotes: 0

Views: 231

Answers (1)

John Ament
John Ament

Reputation: 11723

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.

Upvotes: 1

Related Questions