Skip to content

Commit 7d60dc8

Browse files
committed
feat(concurrency): 🎸 concurrent package, translated
Refers: #8
1 parent d52a7c4 commit 7d60dc8

File tree

6 files changed

+63
-65
lines changed

6 files changed

+63
-65
lines changed
Lines changed: 41 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,73 @@
11
:java-package: src/org/j6toj8/concurrency
22
:section-java-package: ../../../{java-package}
33

4-
=== Pacote `Concurrent`
4+
=== Concurrent package
55

6-
.Objetivo
6+
.Objective
77
--------------------------------------------------
88
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
119
--------------------------------------------------
1210

13-
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.
1412

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.
1614

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.
1816

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.
2018
+
2119
[source,java,indent=0]
2220
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java
2321
----
2422
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java[tag=code]
2523
----
2624

27-
. É possível criar uma *Fila Duplamente Ligada (Deque)* que lança uma exceção após um tempo predefinido utilizando a classe ``LinkedBlockingDeque``.
25+
. You can create a *Double Queue (Deque)* that throws an exception after a preset time using the `LinkedBlockingDeque` class.
2826
+
2927
[source,java,indent=0]
3028
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java
3129
----
3230
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java[tag=code]
3331
----
3432

35-
. É possível criar uma lista que aloca todo o seu conteúdo em um novo _array_ sempre que é modificada utilizando a classe ``CopyOnWriteArrayList``.
33+
. You can create a list that allocates all of its contents to a new _array_ whenever it is modified using the `CopyOnWriteArrayList` class.
3634
+
3735
[source,java,indent=0]
3836
.{java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java
3937
----
4038
include::{section-java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java[tag=code]
4139
----
4240
+
43-
.Saída no console
41+
.console output
4442
[source,console]
4543
----
4644
A
4745
B
4846
C
49-
Lista final: [A, B, C, D]
47+
Final list: [A, B, C, D]
5048
----
5149
+
52-
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`.
5351
+
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_.
5553

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.
5755
+
5856
[source,java,indent=0]
5957
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java
6058
----
6159
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java[tag=code]
6260
----
6361

64-
. *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.
6563
+
6664
[source,java,indent=0]
6765
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java
6866
----
6967
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java[tag=code]
7068
----
7169
+
72-
.Saída no console
70+
.console output
7371
[source,console]
7472
----
7573
Exception in thread "main" java.util.ConcurrentModificationException
@@ -79,52 +77,52 @@ Exception in thread "main" java.util.ConcurrentModificationException
7977
at org.j6toj8.concurrency.concurrentpackage.Concurrency_CollectionsSyncronizedForEach.main(Concurrency_CollectionsSyncronizedForEach.java:18)
8078
----
8179
+
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.
8381

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.
8583
+
8684
[source,java,indent=0]
8785
.{java-package}/concurrentpackage/Concurrency_CyclicBarrier.java
8886
----
8987
include::{section-java-package}/concurrentpackage/Concurrency_CyclicBarrier.java[tag=code]
9088
----
9189
+
92-
.Saída no console
90+
.console output
9391
[source,console]
9492
----
95-
Thread-2: Primeira Parte
96-
Thread-1: Primeira Parte
97-
Thread-0: Primeira Parte
98-
Thread-1: Segunda Parte
99-
Thread-2: Segunda Parte
100-
Thread-0: Segunda Parte
101-
Thread-0: Terceira Parte
102-
Thread-1: Terceira Parte
103-
Thread-2: Terceira Parte
93+
Thread-2: First Part
94+
Thread-1: First Part
95+
Thread-0: First Part
96+
Thread-1: Second Part
97+
Thread-2: Second Part
98+
Thread-0: Second Part
99+
Thread-0: Third Part
100+
Thread-1: Third Part
101+
Thread-2: Third Part
104102
----
105103
+
106-
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:
107105
+
108-
.Saída no console caso não houvesse CyclicBarrier
106+
.console output if there was no CyclicBarrier
109107
[source,console]
110108
----
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
121118
----
122119

120+
.References
123121
****
124122
125123
* Using Concurrent Collections
126124
+
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.
128126
129127
* https://www.baeldung.com/java-util-concurrent[Overview of the java.util.concurrent.]
130128
@@ -134,4 +132,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
134132
135133
* https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html[Package java.util.concurrent.] Java Plataform SE 8.
136134
137-
****
135+
****

src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CollectionsSyncronized.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ public class Concurrency_CollectionsSyncronized {
99

1010
public static void main(String[] args) {
1111
// tag::code[]
12-
// Concurrent Map, garante o acesso de múltiplas threads
12+
// Concurrent Map, ensures multi-threaded access
1313
Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();
1414

15-
// Map Comum, NÃO garante o acesso de múltiplas threads
15+
// Common Map, DOES NOT ensures multi-threaded access
1616
Map<String, String> map = new HashMap<>();
1717

18-
// Syncronized Map, garante o acesso de múltiplas threads
18+
// Syncronized Map, ensures multi-threaded access
1919
Map<String, String> synchronizedMap = Collections.synchronizedMap(map);
2020
// end::code[]
2121
}

src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CopyOnWriteArrayList.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static void main(String[] args) {
1919
}
2020
}
2121

22-
System.out.println("Lista final: " + list);
22+
System.out.println("Final list: " + list);
2323
// end::code[]
2424
}
2525

src/org/j6toj8/concurrency/concurrentpackage/Concurrency_CyclicBarrier.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,47 +6,47 @@
66
public class Concurrency_CyclicBarrier {
77

88
// tag::code[]
9-
// Classe que será executada por 3 threads
10-
static class Acao implements Runnable {
9+
// Class that will be executed by 3 threads
10+
static class Action implements Runnable {
1111

1212
CyclicBarrier cyclicBarrier;
1313

14-
public Acao(CyclicBarrier cyclicBarrier) {
14+
public Action(CyclicBarrier cyclicBarrier) {
1515
this.cyclicBarrier = cyclicBarrier;
1616
}
1717

1818
@Override
1919
public void run() {
20-
System.out.println(Thread.currentThread().getName() + ": Primeira Parte");
20+
System.out.println(Thread.currentThread().getName() + ": First Part");
2121

2222
try {
23-
cyclicBarrier.await(); // sincronização das threads
23+
cyclicBarrier.await(); // thread synchronization
2424
} catch (InterruptedException | BrokenBarrierException e) {
2525
e.printStackTrace();
2626
}
2727

28-
System.out.println(Thread.currentThread().getName() + ": Segunda Parte");
28+
System.out.println(Thread.currentThread().getName() + ": Second Part");
2929

3030
try {
31-
cyclicBarrier.await(); // sincronização das threads
31+
cyclicBarrier.await(); // thread synchronization
3232
} catch (InterruptedException | BrokenBarrierException e) {
3333
e.printStackTrace();
3434
}
3535

36-
System.out.println(Thread.currentThread().getName() + ": Terceira Parte");
36+
System.out.println(Thread.currentThread().getName() + ": Third Part");
3737
}
3838
}
3939

4040
public static void main(String[] args) {
41-
// Criação de um CyclicBarrier para 3 threads
41+
// Creating a CyclicBarrier for 3 threads
4242
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
4343

44-
// Criação das threads
45-
Thread thread1 = new Thread(new Acao(cyclicBarrier));
46-
Thread thread2 = new Thread(new Acao(cyclicBarrier));
47-
Thread thread3 = new Thread(new Acao(cyclicBarrier));
44+
// Thread Creation
45+
Thread thread1 = new Thread(new Action(cyclicBarrier));
46+
Thread thread2 = new Thread(new Action(cyclicBarrier));
47+
Thread thread3 = new Thread(new Action(cyclicBarrier));
4848

49-
// Início de execução das threads
49+
// Threads start running
5050
thread1.start();
5151
thread2.start();
5252
thread3.start();

src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingDeque.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@ public static void main(String[] args) {
1414
queue.offerFirst("ABC", 1, TimeUnit.SECONDS);
1515
queue.offerLast("DEF", 1, TimeUnit.SECONDS);
1616
} catch (InterruptedException e) {
17-
System.out.println("Não conseguiu inserir em menos de 1 segundo.");
17+
System.out.println("Failed to insert in less than 1 second.");
1818
}
1919

2020
try {
2121
queue.pollFirst(1, TimeUnit.SECONDS);
2222
queue.pollLast(1, TimeUnit.SECONDS);
2323
} catch (InterruptedException e) {
24-
System.out.println("Não conseguiu remover em menos de 1 segundo.");
24+
System.out.println("Failed to remove in less than 1 second.");
2525
}
2626
// end::code[]
2727
}

src/org/j6toj8/concurrency/concurrentpackage/Concurrency_LinkedBlockingQueue.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@ public static void main(String[] args) {
1313
try {
1414
queue.offer("ABC", 1, TimeUnit.SECONDS);
1515
} catch (InterruptedException e) {
16-
System.out.println("Não conseguiu inserir em menos de 1 segundo.");
16+
System.out.println("Failed to insert in less than 1 second.");
1717
}
1818

1919
try {
2020
queue.poll(1, TimeUnit.SECONDS);
2121
} catch (InterruptedException e) {
22-
System.out.println("Não conseguiu remover em menos de 1 segundo.");
22+
System.out.println("Failed to remove in less than 1 second.");
2323
}
2424
// end::code[]
2525
}

0 commit comments

Comments
 (0)