Что такое parallel stream java
Кроме последовательных потоков Stream API поддерживает параллельные потоки. Распараллеливание потоков позволяет задействовать несколько ядер процессора (если целевая машина многоядерная) и тем самым может повысить производительность и ускорить вычисления. В то же время говорить, что применение параллельных потоков на многоядерных машинах однозначно повысит производительность — не совсем корректно. В каждом конкретном случае надо проверять и тестировать.
Чтобы сделать обычный последовательный поток параллельным, надо вызвать у объекта Stream метод parallel . Кроме того, можно также использовать метод parallelStream() интерфейса Collection для создания параллельного потока из коллекции.
В то же время если рабочая машина не является многоядерной, то поток будет выполняться как последовательный.
Применение параллельных потоков во многих случаях будет аналогично. Например:
import java.util.Optional; import java.util.stream.Stream; public class Program < public static void main(String[] args) < StreamnumbersStream = Stream.of(1, 2, 3, 4, 5, 6); Optional result = numbersStream.parallel().reduce((x,y)-> x*y); System.out.println(result.get()); // 720 > >
Еще один пример:
import java.util.Arrays; import java.util.List; public class Program < public static void main(String[] args) < Listpeople = Arrays.asList("Tom","Bob", "Sam", "Kate", "Tim"); System.out.println("Последовательный поток"); people.stream().filter(p->p.length()==3).forEach(System.out::println); System.out.println("\nПараллельный поток"); people.parallelStream().filter(p->p.length()==3).forEach(System.out::println); > >
В данном случае сначала для списка people создаем поток и выполняем над ним ряд операций в последовательном режиме. В частности, находим в списке строки, длина которых равна 3 и выводим их на консоль. В этом случае все операции с потоком будут производиться над элементами списка в том порядке, в котоом элементы идут в списке.
Затем с помощью метода people.parallelStream() для списка создается параллельный поток. Причем применяются те же операции, однако теперь порядок, в котором над элементами списка будут производиться операции, не детерминирован.
Последовательный поток Tom Bob Sam Tim Параллельный поток Sam Tim Bob Tom
В случае с параллельным потоком вывод недетерминирован и может отличаться.
Однако не все функции можно без ущерба для точности вычисления перенести с последовательных потоков на параллельные. Прежде всего такие функции должны быть без сохранения состояния и ассоциативными, то есть при выполнении слева направо давать тот же результат, что и при выполнении справа налево, как в случае с произведением чисел. Например:
Stream numbersStream = Stream.of(1, 2, 3, 4, 5, 6); Integer result = numbersStream.parallel().reduce(1, (x,y)->x * y); System.out.println(result);
Фактически здесь происходит перемножение чисел. При этом нет разницы между 1 * 2 * 3 * 4 * (5 * 6) или 5 * 6 * 1 * (2 * 3) * 4 . Мы можем расставить скобки любым образом, разместить последовательность чисел в любом порядке, и все равно мы получим один и тот же результат. То есть данная операция является ассоциативной и поэтому может быть распараллелена.
Вопросы производительности в параллельных операциях
Фактически применение параллельных потоков сводится к тому, что данные в потоке будут разделены на части, каждая часть обрабатывается на отдельном ядре процессора, и в конце эти части соединяются, и над ними выполняются финальные операции. Рассмотрим некоторые критерии, которые могут повлиять на производительность в параллельных потоках:
- Размер данных. Чем больше данных, тем сложнее сначала разделять данные, а потом их соединять.
- Количество ядер процессора. Теоретически, чем больше ядер в компьютере, тем быстрее программа будет работать. Если на машине одно ядро, нет смысла применять параллельные потоки.
- Чем проще структура данных, с которой работает поток, тем быстрее будут происходить операции. Например, данные из ArrayList легко использовать, так как структура данной коллекции предполагает последовательность несвязанных данных. А вот коллекция типа LinkedList — не лучший вариант, так как в последовательном списке все элементы связаны с предыдущими/последующими. И такие данные трудно распараллелить.
- Над данными примитивных типов операции будут производиться быстрее, чем над объектами классов
Упорядоченность в параллельных потоках
Как правило, элементы передаются в поток в том же порядке, в котором они определены в источнике данных. При работе с параллельными потоками система сохраняет порядок следования элементов. Исключение составляет метод forEach() , который может выводить элементы в произвольном порядке. И чтобы сохранить порядок следования, необходимо применять метод forEachOrdered :
phones.parallelStream() .sorted() .forEachOrdered(s->System.out.println(s));
Сохранение порядка в параллельных потоках увеличивает издержки при выполнении. Но если нам порядок не важен, то мы можем отключить его сохранение и тем самым увеличить производительность, использовав метод unordered :
phones.parallelStream() .sorted() .unordered() .forEach(s->System.out.println(s));
What is Java Parallel Streams?
Parallel processing is a cornerstone of modern computing, allowing us to take full advantage of multi-core systems. In the realm of Java, one of the tools at our disposal to utilize this power is parallel streams. This article delves into the concept of parallel streams in Java, exploring their functionality, benefits, and how to use them effectively.
Understanding Java Parallel Streams
Java Streams were introduced in Java 8 as a way to perform complex data processing tasks on collections of objects, often referred to as a stream of data. These operations can be executed sequentially or in parallel. A parallel stream divides the provided task into many and runs them on different threads, utilizing multiple cores of the computer.
Parallel streams use a technique called fork/join, which breaks a complex task into smaller pieces (forking) and then combines the results (joining). This can significantly increase the processing speed, especially when working with large datasets.
Creating Parallel Streams
A parallel stream in Java can be created from any collection or array. Here are some examples
List myList = new ArrayList<>(); // create a parallel stream from a list Stream parallelStream = myList.parallelStream(); // create a parallel stream from an array int[] myArray = new int[10]; IntStream parallelArrayStream = Arrays.stream(myArray).parallel();
Key Methods
Parallel streams can use all the same methods as a regular stream, such as filter(), map(), reduce(), and collect(). However, the execution of these methods in a parallel stream may occur in multiple threads and in no particular order.
When to Use Parallel Streams
While parallel streams can speed up processing time for large datasets, they aren’t always the best choice. For smaller datasets, the overhead of creating and managing multiple threads can actually make parallel streams slower than sequential ones. Therefore, it’s important to consider the size and complexity of your task before deciding to use parallel streams.
Understanding the Risks
Although parallel streams can greatly improve efficiency, they also introduce potential risks. Parallel streams can cause thread-safety issues if the underlying data structures are modified during processing. Additionally, some tasks may not be suitable for parallelization because they rely on a specific order of execution. Therefore, always ensure your task is suitable for parallel processing before creating a parallel stream.
Example of Java Parallel Stream
Here’s an example of using a parallel stream to filter and transform a large list of integers
List intList = new ArrayList<>(); // Populate the list. List processedList = intList.parallelStream() .filter(n -> n % 2 == 0) .map(n -> n * 2) .collect(Collectors.toList());
In this example, the parallelStream() method is used to create a parallel stream from a list. The filter() and map() methods are then used to process the data in parallel, with the results being collected into a new list.
Conclusion
Java parallel streams are a powerful tool that can significantly increase the efficiency of processing large data sets. However, they should be used judiciously, considering factors such as task complexity, data size, and thread safety. With a sound understanding of parallel streams, you can fully exploit the power of modern multi-core systems to enhance your Java applications’ performance.
Parallel Stream in Java
One of the prominent features of Java 8 (or higher) is Java Parallel Stream. It is meant for utilizing the various cores of the processor. Usually, any Java code that has only one processing stream, where it is sequentially executed. However, by using parallel streams, one can separate the Java code into more than one stream, which is executed in parallel on their separate cores, and the end result is the combination of the individual results. The order in which they are executed is not in our control. Hence, it is suggested to use a parallel stream when the order of execution of individual items does not affect the final result.
Analysis of Parallel Stream
For increasing the performance of a program, parallel streams are introduced. However, it is not a guarantee that applying a parallel stream will enhance the result. For example, there can be a scenario where code must be executed in a certain order. There are certain instances in which we need the code to be executed in a certain order, and in such a case, it is required to use sequential streams instead of parallel streams.
Different Ways to Create Stream
There are two ways we can create, which are listed below and described later as follows:
- Using the parallel() method on a stream
- Using parallelStream() on a Collection
Using parallel() method on a stream
The parallel() method of the BaseStream interface returns an equivalent parallel stream. Let’s understand its working through an example.
FileName: ParallelStream.java
Output 1:
Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris. Fusce nulla augue, convallis at velit ac, pulvinar convallis eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed ut ipsum molestie dolor dictum luctus. Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna faucibus mollis. Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.
Explanation: In the above program, we have made a file object that points to a parallelstream.txt file that is already present in the system. After that, a stream is created that does reading from the text file (only one line at a time). Then we invoke the parallel() method to display the content of the parallelstream.txt on the console. Note that the order of the execution is different each time we execute the above code. The code is executed again; the following output is displayed on the console.
Output 2:
Fusce nulla augue, convallis at velit ac, pulvinar convallis eros. Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris. Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna faucibus mollis. Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed ut ipsum molestie dolor dictum luctus.
Using parallelStream() on a Collection
The parallelStream() method is part of the Collection interface and returns a parallel stream with the collection as a source. It’s working of it is explained in the following example.
FileName: ParallelStream.java
Output 1:
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed ut ipsum molestie dolor dictum luctus. Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris. Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna faucibus mollis. Fusce nulla augue, convallis at velit ac, pulvinar convallis eros. Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.
Explanation: In the above-mentioned code, we are using a parallel stream. However, we are using the List to read from the parallelstream.txt file. Hence, the parallelstream() method is required.
Other Examples of Parallel Execution of Stream
Let’s see a few more examples of parallel execution of streams.
FileName: ParallelStream1.java
Output:
In Normal 1 2 3 4 5 In Parallel 3 5 4 2 1
Let’s see another example.
FileName: ParallelStream2.java
Output:
In Normal 1 2 3 4 5 In Parallel 3 5 4 2 1
Java Program to Check Stream is Running Parallel or Not
We can also check whether the stream is running in parallel or not.
FileName: ParallelStream3.java
Output:
In Normal The stream is not running parallelly. 1 2 3 4 5 In Parallel The stream is running parallelly. 3 5 4 1 2
Next Topic Java Convert Bytes to Unsigned Bytes

For Videos Join Our Youtube Channel: Join Now
Feedback
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Python Design Patterns
![]()
![]()
![]()
Preparation




Trending Technologies
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
B.Tech / MCA
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter

Parallel streams
Стримы бывают последовательными ( sequential ) и параллельными ( parallel ). Последовательные выполняются только в текущем потоке, а вот параллельные используют общий пул ForkJoinPool.commonPool() . При этом элементы разбиваются (если это возможно) на несколько групп и обрабатываются в каждом потоке отдельно. Затем на нужном этапе группы объединяются в одну для предоставления конечного результата.
Чтобы получить параллельный стрим, нужно либо вызвать метод parallelStream() вместо stream(), либо превратить обычный стрим в параллельный, вызвав промежуточный оператор parallel() .
list.parallelStream() .filter(x -> x > 10) .map(x -> x * 2) .collect(Collectors.toList());
IntStream.range(0, 10) .parallel() .map(x -> x * 10) .sum();
Работа с потоконебезопасными коллекциями, разбиение элементов на части, создание потоков, объединение частей воедино, всё это кроется в реализации Stream API . От нас лишь требуется вызвать нужный метод и проследить, чтобы функции в операторах не зависели от каких-либо внешних факторов, иначе есть риск получить неверный результат или ошибку.
Вот так делать нельзя:
final List ints = new ArrayList<>(); IntStream.range(0, 1000000) .parallel() .forEach(i -> ints.add(i)); System.out.println(ints.size());
Это код Шрёдингера. Он может нормально выполниться и показать 1000000, может выполниться и показать 869877, а может и упасть с ошибкой
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 666 at java.util.ArrayList.add(ArrayList.java:777).
Поэтому разработчики настоятельно просят воздержаться от побочных эффектов в лямбдах, то тут, то там говоря в документации о невмешательстве ( non-interference ).
- Не используйте параллельные стримы везде, где только можно. Затраты на разбиение элементов, обработку в другом потоке и последующее их слияние порой больше, чем выполнение в одном потоке.
- При использовании параллельных стримов, убедитесь, что нигде нет блокирующих операций или чего-то, что может помешать обработке элементов.
list.parallelStream() .filter(s -> isFileExists(hash(s))) .
