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
We’ve talked about the StepContext and about the persistent and transient user data associated with it. In this entry we’ll have a look at the JobContext and the transient data that goes with it.
First of all, you can inject the JobContext into any batch artifact exactly like we injected the StepContext (using the JobContext class of course).
private JobContext jobContext;
This results in the jobContext variable being set to the JobContext object for this job. Mostly. Remember that the StepContext was a single object for the Step, unless the step is a partitioned step in which case each partition got a separate instance of the StepContext object? Well, the JobContext works much the same way. There is a JobContext object for the main thread of the job, but there are also separate JobContext objects for separate threads of execution in the job.
This is really important because the JobContext isn’t necessarily as ‘global’ to the job as you might hope. Each partition of a partitioned step and each flow of a split/flow will get a separate JobContext object. I bring this up first because it makes the second part of this entry somewhat less exciting than I’d like.
The JobContext has a bunch of methods on it, but the two of interest here are
getTransientUserData and setTransientUserData.
These methods allow you to get and set any object into the JobContext and it is there for the life of this job execution. That means that if the job fails and is restarted, the transient user data, being transient, is gone for the restart.
But it feels like this would be a great way to pass data between steps in the job. And it is, as long as you stay away from the parallel execution features of JSR-352. So you can have Step1 of a job set any object you like into the JobContext transient user data and have Step2 get that same object back out. Passing data between steps is a very common thing to need to do and being able to do it without writing it to a file or a database or something is really quite handy.
Just remember that if the getter and the setter aren’t running on the same thread, you won’t have the same JobContext object and the data won’t make the trip. >>Next article in this series
<<Previous article in this series