Skip to content

Commit

Permalink
feat(concurrency): 馃幐 concurrent package, translated
Browse files Browse the repository at this point in the history
Refers: #8
  • Loading branch information
rcmoutinho committed Sep 12, 2019
1 parent d52a7c4 commit 7d60dc8
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 65 deletions.
84 changes: 41 additions & 43 deletions book/06-concurrency/sections/01-concurrent-package.asc
Original file line number Diff line number Diff line change
@@ -1,75 +1,73 @@
:java-package: src/org/j6toj8/concurrency
:section-java-package: ../../../{java-package}

=== Pacote `Concurrent`
=== Concurrent package

.Objetivo
.Objective
--------------------------------------------------
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
-
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.
The `java.util.concurrent` package includes numerous classes for use in multi-threaded applications. In this section, some of these classes will be presented.

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

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

. 脡 poss铆vel criar uma *Fila* que lan莽a uma exce莽茫o ap贸s um tempo predefinido utilizando a classe ``LinkedBlockingQueue``.
. You can create a *Queue* that throws an exception after a predefined time using the `LinkedBlockingQueue` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java
----
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingQueue.java[tag=code]
----

. 脡 poss铆vel criar uma *Fila Duplamente Ligada (Deque)* que lan莽a uma exce莽茫o ap贸s um tempo predefinido utilizando a classe ``LinkedBlockingDeque``.
. You can create a *Double Queue (Deque)* that throws an exception after a preset time using the `LinkedBlockingDeque` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java
----
include::{section-java-package}/concurrentpackage/Concurrency_LinkedBlockingDeque.java[tag=code]
----

. 脡 poss铆vel criar uma lista que aloca todo o seu conte煤do em um novo _array_ sempre que 茅 modificada utilizando a classe ``CopyOnWriteArrayList``.
. You can create a list that allocates all of its contents to a new _array_ whenever it is modified using the `CopyOnWriteArrayList` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java
----
include::{section-java-package}/concurrentpackage/Concurrency_CopyOnWriteArrayList.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
A
B
C
Lista final: [A, B, C, D]
Final list: [A, B, C, D]
----
+
Perceba que foi poss铆vel acrescentar um valor na lista durante a execu莽茫o do _forEach_. Em uma lista tradicional haveria ocorrido uma ``ConcurrentModificationException``.
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`.
+
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.
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_.

. 脡 poss铆vel criar vers玫es _syncronized_ de cole莽玫es utilizando m茅todos utilit谩rios da classe ``Collections``.
. You can create _synchronized_ versions of collections using utility methods of the `Collections` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java
----
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronized.java[tag=code]
----

. *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``.
. *Cannot* add or remove elements during _forEach_ from a synchronized collection that was created using the `Collections` class method.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java
----
include::{section-java-package}/concurrentpackage/Concurrency_CollectionsSyncronizedForEach.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
Exception in thread "main" java.util.ConcurrentModificationException
Expand All @@ -79,52 +77,52 @@ Exception in thread "main" java.util.ConcurrentModificationException
at org.j6toj8.concurrency.concurrentpackage.Concurrency_CollectionsSyncronizedForEach.main(Concurrency_CollectionsSyncronizedForEach.java:18)
----
+
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.
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.

. 脡 poss铆vel sincronizar a execu莽茫o de v谩rias _threads_ utilizando a classe ``CyclicBarrier``.
. You can synchronize the execution of multiple _threads_ using the `CyclicBarrier` class.
+
[source,java,indent=0]
.{java-package}/concurrentpackage/Concurrency_CyclicBarrier.java
----
include::{section-java-package}/concurrentpackage/Concurrency_CyclicBarrier.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
Thread-2: Primeira Parte
Thread-1: Primeira Parte
Thread-0: Primeira Parte
Thread-1: Segunda Parte
Thread-2: Segunda Parte
Thread-0: Segunda Parte
Thread-0: Terceira Parte
Thread-1: Terceira Parte
Thread-2: Terceira Parte
Thread-2: First Part
Thread-1: First Part
Thread-0: First Part
Thread-1: Second Part
Thread-2: Second Part
Thread-0: Second Part
Thread-0: Third Part
Thread-1: Third Part
Thread-2: Third Part
----
+
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`:
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:
+
.Sa铆da no console caso n茫o houvesse CyclicBarrier
.console output if there was no CyclicBarrier
[source,console]
----
Thread-0: Primeira Parte
Thread-1: Primeira Parte
Thread-1: Segunda Parte
Thread-1: Terceira Parte
Thread-2: Primeira Parte
Thread-0: Segunda Parte
Thread-2: Segunda Parte
Thread-0: Terceira Parte
Thread-2: Terceira Parte
Thread-0: First Part
Thread-1: First Part
Thread-1: Second Part
Thread-1: Third Part
Thread-2: First Part
Thread-0: Second Part
Thread-2: Second Part
Thread-0: Third Part
Thread-2: Third Part
----

.References
****
* Using Concurrent Collections
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Edi莽茫o do Kindle.
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 358). Wiley. Kindle Edition.
* https://www.baeldung.com/java-util-concurrent[Overview of the java.util.concurrent.]
Expand All @@ -134,4 +132,4 @@ Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8
* https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html[Package java.util.concurrent.] Java Plataform SE 8.
****
****
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ public class Concurrency_CollectionsSyncronized {

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

// Map Comum, N脙O garante o acesso de m煤ltiplas threads
// Common Map, DOES NOT ensures multi-threaded access
Map<String, String> map = new HashMap<>();

// Syncronized Map, garante o acesso de m煤ltiplas threads
// Syncronized Map, ensures multi-threaded access
Map<String, String> synchronizedMap = Collections.synchronizedMap(map);
// end::code[]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static void main(String[] args) {
}
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,47 @@
public class Concurrency_CyclicBarrier {

// tag::code[]
// Classe que ser谩 executada por 3 threads
static class Acao implements Runnable {
// Class that will be executed by 3 threads
static class Action implements Runnable {

CyclicBarrier cyclicBarrier;

public Acao(CyclicBarrier cyclicBarrier) {
public Action(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}

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

try {
cyclicBarrier.await(); // sincroniza莽茫o das threads
cyclicBarrier.await(); // thread synchronization
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}

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

try {
cyclicBarrier.await(); // sincroniza莽茫o das threads
cyclicBarrier.await(); // thread synchronization
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName() + ": Terceira Parte");
System.out.println(Thread.currentThread().getName() + ": Third Part");
}
}

public static void main(String[] args) {
// Cria莽茫o de um CyclicBarrier para 3 threads
// Creating a CyclicBarrier for 3 threads
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

// Cria莽茫o das threads
Thread thread1 = new Thread(new Acao(cyclicBarrier));
Thread thread2 = new Thread(new Acao(cyclicBarrier));
Thread thread3 = new Thread(new Acao(cyclicBarrier));
// Thread Creation
Thread thread1 = new Thread(new Action(cyclicBarrier));
Thread thread2 = new Thread(new Action(cyclicBarrier));
Thread thread3 = new Thread(new Action(cyclicBarrier));

// In铆cio de execu莽茫o das threads
// Threads start running
thread1.start();
thread2.start();
thread3.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ public static void main(String[] args) {
queue.offerFirst("ABC", 1, TimeUnit.SECONDS);
queue.offerLast("DEF", 1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("N茫o conseguiu inserir em menos de 1 segundo.");
System.out.println("Failed to insert in less than 1 second.");
}

try {
queue.pollFirst(1, TimeUnit.SECONDS);
queue.pollLast(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("N茫o conseguiu remover em menos de 1 segundo.");
System.out.println("Failed to remove in less than 1 second.");
}
// end::code[]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ public static void main(String[] args) {
try {
queue.offer("ABC", 1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("N茫o conseguiu inserir em menos de 1 segundo.");
System.out.println("Failed to insert in less than 1 second.");
}

try {
queue.poll(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println("N茫o conseguiu remover em menos de 1 segundo.");
System.out.println("Failed to remove in less than 1 second.");
}
// end::code[]
}
Expand Down

0 comments on commit 7d60dc8

Please sign in to comment.