AsyncResponse and Java 8 parallel stream issue

╄→尐↘猪︶ㄣ 提交于 2019-12-22 10:59:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!