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 Job Listener is the only one that can be specified in the <listener> element at the <job> level. Of course, as we noted last time, you can have more than one of them if you want.
The Job Listener is very cool because it is the very first and the very last opportunity for you to get control for a job. The beforeJob method will get control before anything else happens in the job. The afterJob method will get control after everything else is done in the job. It is the very last chance you have to do something in the job.
What sort of things might you want to do? Well, in the beforeJob method you can do any sort of setup or initialization that is required for things later in the job. You might also be able to do some verification or validation to be sure you want to actually let the job run. Perhaps some resource needs to be available or it is pointless to continue. An exception thrown from the beforeJob method will stop the job cold.
The afterJob method is probably more interesting. Of course it can act as the mirror for the beforeJob method and tear down and clean up any sort of setup thing that got done at the start of the job. But it also serves as your last chance to set the job’s Exit Status.
We’ve talked about this a bit in an earlier post. The afterJob method in the Job Listener is the only batch artifact that gets control on the way out of the job and can set an overall Exit Status value for the entire job. If you plan to use it this way, you’ll need to give some thought to how you will communicate the overall success of the job to the Listener. It doesn’t receive any parameters, but you do know that the afterJob method will run on the same thread that has been acting as the main job thread all along. Of course partitions and splits might have caused some parts to run on other threads (and maybe in different processes entirely).
One last thing to ponder about the afterJob method: it always gets control! The spec says that even if some other bit of the job throws an unhandled exception, the afterJob method will still get control. That means that you can be sure that it will have an opportunity to set the Exit Status and do any required cleanup – if it can determine what it needs to do – it isn’t passed the error that happened.