title: Spring batch: Executing multiple instance of a job in parallel with stateful beans
body: <p>Here is my use case:</p>
  
  <p>I have a code library (stateful) and I want to execute my spring batch job in parallel to
  process data more than 1 record at the same time. But since my library is non thread safe, it would be impossible to use multi threading for running the batch without adding a custom setup. </p>
  
  <p>Also, the code library is called during the ItemProcess of the job.</p>
  
  <p>Here what I have tried so far:</p>
  
  <ol>
  <li><p>I added a <code>@Scope("step")</code> in every java file that is stateful. This works fine in parellel except that performance greatly degrades. Even if there's only 1 thread, having <code>@Scope("step")</code> in the stateful beans degrade performance.</p>
  
  <p>For example: 
    100 data in 1 thread with no <code>@Scope("step")</code> processes data in 2 minutes.
    100 data in 1 thread with <code>@Scope("step)</code> process data in 4 minutes. </p>
  
  <p>(I don't know if there are overheads added when <code>@Scope("step")</code> is used)</p></li>
  <li><p>For every data I received/read, I create a new <code>ClassPathXmlApplicationContext</code> and uses a JobLauncher with <code>ThreadPoolTaskExecutor</code> but somehow I get <code>NullPointerException</code> when running. It seems that some methods are already called even if the init() method was still not called. init() method is called by a service class to initialize the data of the stateful jobs. I also verified that I was indeed creating new instances of the code library per thread (verified by checking the hashCode of object) but I couldn't explain why it was not calling it's method sequentially. Note that JobLauncher is declared in every applicationContext.</p></li>
  <li><p>I remove the JobLauncher and placed it in a parent applicationContext to have a singleton of JobLauncher. I'm still creating the applicationContext per data but I am adding the parent applicationContext during creation. JobLauncher is still <code>ThreadPoolTaskExecutor</code> but I set the <code>tasklet-executor</code> of the tasklet of my job to <code>SyncTaskExecutor</code>. When I ran it, it freezes at some point (console in my eclipse has stop updating)</p></li>
  </ol>
  
  <p>As much as possible, I would not want to refactor the library code to change it to thread safe since this library was made by another team.</p>
  
  <p>What should be the best approach when dealing with stateful beans in an multi threading environment?</p>
  
  <p>Thanks in advance.</p>