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
Use classes from the java.util.concurrent package including CyclicBarrier and CopyOnWriteArrayList with a focus on the advantages over and differences from the traditional java.util collections
9
-
-
10
-
Usar classes do pacote java.util.concurrent, incluindo CyclicBarrier e CopyOnWriteArrayList, com foco nas vantagens e diferenças das Coleções tradicionais do pacote java.util
O pacote `java.util.concurrent` inclui inúmeras classes para serem utilizadas em aplicações multi-thread. Nesta seção serão apresentadas algumas dessas classes.
11
+
The `java.util.concurrent` package includes numerous classes for use in multi-threaded applications. In this section, some of these classes will be presented.
14
12
15
-
Muitas das classes do pacote concurrent são apenas versões das coleções comuns, porém com blocos __syncronized__, garantindo que múltiplas _threads_ poderão acessá-las ao mesmo tempo mantendo sua integridade. As classes __ConcurrentHashMap__, _ConcurrentLinkedQueue_ e _ConcurrentLinkedDeque_ são exemplos disso. Por isso é importante conhecer e lembrar das coleções comuns do Java 6.
13
+
Many of the concurrent package classes are just versions of the common collections, but with _synchronized_ blocks, ensuring that multiple _threads_ can access them while maintaining their integrity. The _ConcurrentHashMap_, _ConcurrentLinkedQueue_, and _ConcurrentLinkedDeque_ classes are examples of this. That's why it's important to know and remember the common Java 6 collections.
16
14
17
-
Todas as seções deste capítulo podem conter exemplos maiores do que os que foram apresentados até agora, principalmente quando for necessário a criação de mútiplas __Threads__. É importante dedicar um tempo maior para entender cada um desses exemplos.
15
+
All sections of this chapter may contain larger examples than presented so far, especially when creating multiple _Threads_ is required. It is important to spend more time understanding each of these examples.
18
16
19
-
. É possível criar uma *Fila* que lança uma exceção após um tempo predefinido utilizando a classe ``LinkedBlockingQueue``.
17
+
. You can create a *Queue* that throws an exception after a predefined time using the `LinkedBlockingQueue` class.
Perceba que foi possível acrescentar um valor na lista durante a execução do _forEach_. Em uma lista tradicional haveria ocorrido uma ``ConcurrentModificationException``.
50
+
Note that it was possible to add a value to the list during _forEach_ execution. In a traditional list there would have been a `ConcurrentModificationException`.
53
51
+
54
-
Perceba também que, mesmo alterando a lista dentro do __forEach__, a letra "D" não aparece no console. Isso ocorre pois, quando a letra "D" foi inserida na lista, um novo _array_ foi alocado internamente contendo todos os novos elementos, e a iteração continuou ocorrendo no _array_ antigo.
52
+
Also note that even if you change the list within _forEach_, the letter "D" does not appear on the console. This is because when the letter "D" was entered in the list, a new _array_ was internally allocated containing all the new elements, and the iteration continued to occur in the old _array_.
55
53
56
-
. É possível criar versões _syncronized_ de coleções utilizando métodos utilitários da classe ``Collections``.
54
+
. You can create _synchronized_ versions of collections using utility methods of the `Collections` class.
. *Não* é possível adicionar ou remover elementos durante o _forEach_ de uma coleção sincronizada que foi criada utilizando o método da classe ``Collections``.
62
+
. *Cannot* add or remove elements during _forEach_ from a synchronized collection that was created using the `Collections` class method.
Exception in thread "main" java.util.ConcurrentModificationException
@@ -79,52 +77,52 @@ Exception in thread "main" java.util.ConcurrentModificationException
79
77
at org.j6toj8.concurrency.concurrentpackage.Concurrency_CollectionsSyncronizedForEach.main(Concurrency_CollectionsSyncronizedForEach.java:18)
80
78
----
81
79
+
82
-
Perceba que, apesar do `Map` ter sido transformado em __syncronized__, não é possível alterá-lo durante uma iteração com __forEach__. Isso é possível apenas nas versões _Concurrent_ das coleções.
80
+
Note that although `Map` has been turned into _synchronized_, it cannot be changed during an iteration with _forEach_. This is only possible in _Concurrent_ versions of collections.
83
81
84
-
. É possível sincronizar a execução de várias _threads_ utilizando a classe ``CyclicBarrier``.
82
+
. You can synchronize the execution of multiple _threads_ using the `CyclicBarrier` class.
Neste exemplo estão sendo criadas 3 __threads__. Todas executam instâncias da classe `Acao` que recebem a mesma instância da classe ``CyclicBarrier``. Toda vez que uma _thread_ faz uma chamada ao método `await` da instância de ``cyclicBarrier``, ela fica suspensa até que todas as outras _threads_ cheguem até aquele mesmo ponto. Por isso todas as _threads_ imprimem no console de forma sincronizada. Se não houvesse sincronização, a saída no console seria completamente imprevisível. Abaixo é o exemplo de uma execução sem a chamada ao método `await`:
104
+
In this example 3 _threads_ are being created. All run instances of the `Action` class that receive the same instance of the `CyclicBarrier` class. Every time a _thread_ calls the `await` method of the `cyclicBarrier` instance, it is suspended until all other _threads_ reach that same point. That's why all _threads_ print to the console synchronously. If there was no synchronization, the console output would be completely unpredictable. Below is an example of an execution without calling the `await` method:
107
105
+
108
-
.Saída no console caso não houvesse CyclicBarrier
106
+
.console output if there was no CyclicBarrier
109
107
[source,console]
110
108
----
111
-
Thread-0: Primeira Parte
112
-
Thread-1: Primeira Parte
113
-
Thread-1: Segunda Parte
114
-
Thread-1: Terceira Parte
115
-
Thread-2: Primeira Parte
116
-
Thread-0: Segunda Parte
117
-
Thread-2: Segunda Parte
118
-
Thread-0: Terceira Parte
119
-
Thread-2: Terceira Parte
120
-
109
+
Thread-0: First Part
110
+
Thread-1: First Part
111
+
Thread-1: Second Part
112
+
Thread-1: Third Part
113
+
Thread-2: First Part
114
+
Thread-0: Second Part
115
+
Thread-2: Second Part
116
+
Thread-0: Third Part
117
+
Thread-2: Third Part
121
118
----
122
119
120
+
.References
123
121
****
124
122
125
123
* Using Concurrent Collections
126
124
+
127
-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Edição do Kindle.
125
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Kindle Edition.
128
126
129
127
* https://www.baeldung.com/java-util-concurrent[Overview of the java.util.concurrent.]
130
128
@@ -134,4 +132,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
134
132
135
133
* https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html[Package java.util.concurrent.] Java Plataform SE 8.
0 commit comments