简体   繁体   中英

Why the stream doesn't work in parallel mode?

I have a code :

rows = types.stream().parallel().map(s -> {
    switch (s){
        case NDBaseDocumentModel.DOC_TYPE_NSS:
            return getDocsOfSpecificTypeAndCountItsDupes(NDGostStandardsModel.TYPE_ND_GOST_STANDARDS, null,systemMessages.getString("form20.nss.name")).values();
        case NDBaseDocumentModel.DOC_INT_REG_STANDARDS:
            return getDocsOfSpecificTypeAndCountItsDupes(NDIntRegStandardsModel.TYPE_ND_INT_REG_STANDARDS, null,systemMessages.getString("form20.int_reg")).values();
    }
    return new HashSet<Form20Row>();
}).flatMap(o -> {
    return o.stream();
}).collect(Collectors.toList());

And it doesn't work (return zero rows), but work fine when I remove "parallel()" call (14 rows on same data). Could somebody tell me why, please?? Please?

Parallel streams are processed using a thread pool, and as such your method getDocsOfSpecificTypeAndCountItsDupes needs to be thread-safe.

As removing the parallel() and processing it on the same thread fixes your issue, it seems likely that there's something in the method that isn't thread-safe, which will be your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM