问题
I am using spring boot with Jersey rest api
@POST
@Path("test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void test(final List<String> requests, @Suspended final AsyncResponse asyncResponse) {
List<String> resplist = new ArrayList();
requests.parallelStream().forEach(req -> {
String resp = //some process to get (Always return string)
resplist.add(resp);
});
asyncResponse.resume(resplist);
}
If I use parallelStream sometimes the list that is retrieved on the client side does not return all the elements.
Lets say I pass 30 it returns 29 but sometime it does return 30 (Request is always the same)
But If I use normal stream with forEach only, then it always returns me 30 elements.
Is this some sort of bug? Can I not use parallelStream in rest api
UPDATE
As answered by Eugene this was the issue because when using parallel stream multiple threads were adding record into arraylist which is not threadsafe
solution Use Synch collection
Collection<String> resplist = Collections.synchronizedCollection(new ArrayList<String>());
回答1:
As far as I can see you are relying on side-effects here in the part:
.forEach(req -> {
String resp = //some process to get (Always return string)
resplist.add(resp);
});
You are spawning multiple threads to add elements to a non-thread-safe collection such as ArrayList.
You should instead collect those via .collect(Collectors.toList())
来源:https://stackoverflow.com/questions/46630802/asyncresponse-and-java-8-parallel-stream-issue