WebSphere Application Server & Liberty

JSR-352 (Java Batch) Post #12: An Introduction to Listeners

By David Follis posted Tue September 04, 2018 05:20 PM


This post is part of a series delving into the details of the JSR-352 (Java Batch) specification. Each post examines a very specific part of the specification and looks at how it works and how you might use it in a real batch application.

To start at the beginning, follow the link to the first post.

The next post in the series is here.
The JSR-352 specification includes a whole list of things called Listeners.  We’ll look at some of them more closely in upcoming posts, but before we get into details, what is a Listener?

A Listener is a batch artifact that can get control at various points in the processing of a batch job.  The simplest Listener is the Job Listener.  It has methods that get control before and after the job.  The other Listeners provide a way to implement code that gets control at other interesting points.  If you find yourself wishing you could just run a little bit of code between when “this” happens and “that” happens, look for a listener.

All of the Listeners have a way to get control before and after whatever thing for which they are a Listener.  Many of them have an additional method that gets control when an error occurs.  For example, the ItemReadLister has an onReadError method that gets control if the ItemReader throws an exception. 

To specify a Listener, just include it in a <listener> element inside the <listeners> element inside the <step> (or the <job> for the Job level Listener).  What you don’t have to specify is which Listener it is.  The JSL doesn’t care.  Just give it the list of all the Listeners you want to get control and the batch container will figure out which class implements which Listener interface and do the right thing.

You can also specify more than one of the same Listener.  For example, a given Step could have two StepListeners that will both get control.  Be careful with this.  If more than one Listener of the same type is specified there is no guarantee they will get control in the order they were specified (or any other order!). 

To implement a Listener, just code up a Java class that implements the interface (and then specify it in the JSL).  But…a Java class can implement multiple interfaces.  Can one Java class actually implement multiple Listener interfaces?  Sure.  When you specify the class in the JSL the batch container will discover which Listener interfaces it implements and call the right methods whenever appropriate.  If you look carefully at the Listener interfaces you’ll see that the method names were carefully specified so they won’t collide if one class implements more than one interface. 

And that’s the basics of Listeners.  Next we’ll get into how to use specific ones...

<<Previous article in this series