3

I was wondering if next scenario is thread-safe: I have a spring controller with method

@Autowired
private JobService jobService;
    
public String launch(@ModelAttribute("profile") Profile profile){
    JobParameters jobParams = MyUtils.transform(profile);
    jobService.launch(profile.getJobName(), jobParams);
    return "job";
}

and I have MyUtils class with static method that transforms one kind of object to another... like so :

public class MyUtils {
    public static JobParameters transform(Profile profile) {
        JobParametersBuilder jpb = new JobParametersBuilder();
        jpb.addString("profile.name", profile.getProfileName());
        jpb.addString("profile.number", String.valueOf(profile.getNumber()));
        return jpb.toJobParameters();
    }
}

Classes JobParametersBuilder , JobParameters and JobService are from spring batch core project. Profile class is simple POJO.

The question really is... is this static method transform thread-safe since it is dealing with object instances, although all of those instances are locally created for the method.

gunjasal
  • 29
  • 2
  • 9
tibortru
  • 692
  • 5
  • 26
  • 5
    Since your `Profile` class isn't altered elsewhere (by looking at your code) and your static utility method is stateless, it only operates on local variables and arguments, therefore it's thread-safe – JuniorDev Apr 23 '15 at 21:42
  • I thought so. But wasn't sure ... thanks. – tibortru Apr 23 '15 at 22:35

1 Answers1

2

This concrete code IS thread safe if some conditions are met. Here is explanation:

  1. launch method is called from Spring boot controller. Every call that comes to Spring boot controller is called from different thread and that thread is taking execution to the end of the call stack(unless you call some asynchronous call inside that thread). Tomcat can handle 200 threads in same time by default. Which means you can have 200 calls to your Controllers in same time and they will all be in separate threads. Which means launch is thread safe.

  2. Profile is passed to the transform method and if it is simple POJO it is thread safe, because on every call it will be new instance of Profile.

  3. Inside transform method you are instantiate JobParametersBuilder every time which is thread safe if code inside toJobParameters is thread safe and doesn't keep any state of the JobParametersBuilder class or some other.

mommcilo
  • 956
  • 11
  • 28