Java Parallel Stream Usage

Source: Internet
Author: User

The first excerpt about collection concurrency:

One difficulty in implementing parallelism in applications so use collections was that collections be not Thread-safe, W Hich means that multiple threads cannot manipulate a collection without introducing thread interference or memory consiste ncy errors. The collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collectio N, making it thread-safe. However, synchronization introduces thread contention. You want to avoid thread contention because it prevents threads from running in parallel. Aggregate operations and parallel streams enable you to implement parallelism with Non-thread-safe collections provided th At your do not modify the collection while you are operating on it.

This passage can explain why you need to parallel stream.

Here's a look at how to use the parallel stream, with two ways to call it:

1.

Double average = roster    . Parallelstream ()    . Filter (P-p.getgender () = = Person.Sex.MALE)    . Maptoint ( Person::getage)    . Average ()    . getasdouble ();

  

2.

Double average = roster    . Stream ().  Parallel()    . Filter (P-p.getgender () = = Person.Sex.MALE)    . Maptoint (person::getage)    . Average ()    . getasdouble ();

  

There is also a question about sorting, the following code using Foreachordered can be guaranteed order, with the general foreach is not guaranteed order:

Listofintegers    . Parallelstream ()    . foreachordered (E-System.out.print (E + ""));

  

Java Parallel Stream Usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.