You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
_Streams_ podem ser sequenciais ou paralelos. Os sequencias foram vistos na seção anterior, enquanto os paralelos serão apresentados nesta seção. _Streams_ paralelos são executados por mais de uma _Thread_, geralmente uma quantidade igual à quantidade de núcleos do processador onde a aplicação está sendo executada. Apesar disso, nem sempre é útil utilizá-los. Seu ganho real é em _Streams_ com grande volumes de dados. Em um _Stream_ pequeno, transformá-lo em paralelo pode até causar uma perda de performance.
11
+
_Streams_ can be sequential or parallel. Sequential was seen in the previous section, while parallels will be presented in this section. Parallel _Streams_ are executed by more than one _Thread_, usually equal to the number of processor cores where the application is running. Nevertheless, it is not always useful to use them. Your actual gain is _Streams_ using large volumes of data. In a small _Stream_, turning it parallel can even cause a loss of performance.
14
12
15
-
Ao utilizar qualquer tipo de _Stream_, é recomendável não executar funções lambdas que causem efeitos colaterais, como mudanças no estado de objetos. Em _Streams_ paralelos essa recomendação é ainda mais importante.
13
+
When using any kind _Stream_, it is recommended not to perform Lambda functions that cause side effects, such as changes in the state of objects. In parallel _Streams_, this recommendation is even more important.
16
14
17
-
. É possível transformar qualquer _Stream_ em paralelo utilizando o método `parallel`.
15
+
. You can make any _Stream_ parallel using the `parallel` method.
Perceba que na máquina onde o código foi executado, a execução em paralelo demorou apenas 15% do tempo da execução sequencial. Esse não é um teste minucioso, mas mostra o potencial de _Streams_ paralelos.
90
+
Note that on the machine where the code was executed, parallel execution took only 15% of the sequential execution time. This is not a thorough test, but it does show the potential of parallel _Streams_.
93
91
94
-
. Operações intermediárias que alteram o estado de objetos podem gerar resultados inesperados ao serem executadas em paralelo.
92
+
. Intermediate operations that change the state of objects can produce unexpected results when executed in parallel.
Perceba que a ordem foi respeitada na última operação do _Stream_, o `forEachOrdered`, mas não foi respeitada na execução da operação intermediária `map`. Isso ocorre porque essa operação intermediária não precisa seguir a ordem dos itens do stream.
113
+
Note that the order was respected in the last _Stream_ operation, `forEachOrdered`, but was not respected when performing the `map` intermediate operation. This is because this intermediate operation does not have to follow the order of stream items.
116
114
117
-
. Diferente da execução em um _Stream_ sequencial, a operação `findAny` traz resultados realmente aleatórios ao ser executada em um _Stream_ paralelo.
115
+
. Unlike running in a sequential _Stream_, the `findAny` operation brings really random results when executed in a parallel _Stream_.
Perceba que o resultado com o Stream sequencial é idêntico ao paralelo. Isso ocorre porque a operação de multiplicação é associativa, ou seja, fazer `(2 x 2) x (3 x 3)` é o mesmo que fazer `(2 x 2 x 3) x 3`, ou até mesmo `2 x (2 x 3) x 3`.
145
+
Note that the result with sequential Stream is identical to parallel. This is because the multiplication operation is associative, i.e., doing `(2 x 2) x (3 x 3)` is the same as doing `(2 x 2 x 3) x 3`, or even `2 x (2x3) x3`.
148
146
149
-
. Ao realizar uma operação de reduce acumuladores não-associativos irá gerar resultados inesperados.
147
+
. Performing a reduce non-associative accumulator operation will produce unexpected results.
Isso ocorre pois a operação de subtração não é associativa, então o resultado pode variar conforme o _Stream_ for "fatiado" para ser executado em paralelo. Ou seja, fazer `1 - 2 - 3 - 4` não é o mesmo que fazer `(1 - 2) - (3 - 4)`.
162
+
This is because the subtraction operation is not associative, so the result may vary as _Stream_ is "sliced" to run in parallel. That is, doing `1 - 2 - 3 - 4` is not the same as doing `(1 - 2) - (3 - 4)`.
165
163
166
-
. Para coletar o resultado de um _Stream_ paralelo em um mapa, utilize a operação `toConcurrentMap`.
164
+
. To collect the result of a parallel _Stream_ on a map, use the `toConcurrentMap` operation.
Perceba que o resultados das operações pode ser diferente. Ao utilizar o _Collector_ `toConcurrentMap` em um _Stream_ paralelo, as operações podem ser executadas em qualquer ordem e não há necessidade de criar múltiplos `Map's` para serem combinados posteriormente. Em grandes _Streams_, isso pode ocasionar em um ganho de performance.
179
+
Note that the results of operations may differ. By using _Collector_ `toConcurrentMap` in a parallel _Stream_, operations can be performed in any order and there is no need to create multiple `Map's` to be combined later. In large _Streams_, this can lead to a performance gain.
182
180
183
-
. Para coletar o resultado de um Stream paralelo utilize _groupingByConcurrent_ ao invés de _groupingBy_.
181
+
. To collect the result of a parallel stream use _groupingByConcurrent_ instead of _groupingBy_.
Pelo mesmo motivo do exemplo anterior, a ordem pode variar ao utilizar o `groupingByConcurrent`, porém pode haver ganho de performance em grandes _Streams_ paralelos, pois a ordem não é necessariamente seguida e não há necessidade de criar múltiplos mapas.
196
+
For the same reason as in the previous example, the order may vary when using `groupingByConcurrent`, but there may be performance gains on large parallel _Streams_ as the order is not necessarily followed and there is no need to create multiple maps.
199
197
200
-
.Referências
198
+
.References
201
199
****
202
200
203
201
* Working with Parallel Streams
204
202
+
205
-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 366). Wiley. Edição do Kindle.
203
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 366). Wiley. Kindle Edition.
206
204
207
205
* https://www.baeldung.com/java-8-streams[The Java 8 Stream API Tutorial.]
208
206
@@ -212,4 +210,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
212
210
213
211
* https://docs.oracle.com/javase/8/docs/api/?java/util/stream/Stream.html[Interface Stream<T>.] Java Plataform SE 8.
0 commit comments