I have a Javascript which sends multiple ajax requests at the same time. These requests are loading data which is stored in another object that is stored in the session. My problem is that the different requests overwrite each other loaded data because they can not share the loaded data.
I have altered the real code to make it more understandable. The Traincontainer has multiple Train-objects with an unique trainNr. Then the persons for that train get loaded and stored in that object. After that the container ist written back to the session.
What is the best approach to make this thread safe?
@GET @Path(value = "trains/{trainNr}/persons")
@Produces({MediaType.APPLICATION_JSON})
public List<Person> loadPersons(@Context HttpServletRequest request, @PathParam("trainNr") String trainNr) {
// load data
TrainContainer trainContainer = request.getSession().getAttribute("trainContainer");
List<Person> persons = trainService.loadPersons(trainContainer, trainNr);
// update session attribute
request.getSession().setAttribute("trainContainer", trainContainer);
return persons;
}
UPDATE: The Train object inside the trainContainer gets altered in loadPersons thats the reason to store the container back to the session. the different calls overwrite the loaded persons because they dont know of each other and at the end only the persons from the last requests are stored in the session