BatchEE: avoid CDI integration issues


If you use BatchEE as JBatch implementation with a EE container which doesn’t integrate directly with it you can get some surprises like not using the right bean manager or just getting errors about CDI context.

This is because by default BatchEE uses its own pool of threads as needed by the spec but then in these threads CDI is not initialized and the lazy lookup of the bean manager done by BatchEE to avoid to use a “startup” bean manager at runtime in some – expensive – containers can fail cause of it.

To workaround it the easiest is to force BatchEE to do a CDI lookup in the right context. This lookup doesn’t have to work but it will just trigger the loading of the “runtime” bean manager in the right context.

To do so you can use the following @Singleton:

@Startup
@Singleton
public class BatchEEBeanManagerInitializer {
    @PostConstruct
    private void forceInitOfTheBm() {
        try {
            ServicesManager.find().service(BatchArtifactFactory.class).load("something not existing is better");
        } catch (final Exception e) {
            // ok to fail, init is done in a managed thread so all is fine
        }
    }
}

As you can see we use a name which will unlikely match a real bean to avoid to force the initialization of any bean.

Once this bean is called you can start any batch since the CDI BeanManager of BatchEE is correctly initialized.

Note: in TomEE 7 this is useless since the container takes care of the integration :).

Happy Batching ;).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s