Skip to content

Commit

Permalink
feat(concurrency): 馃幐 locks, translated
Browse files Browse the repository at this point in the history
Refers: #8
  • Loading branch information
rcmoutinho committed Sep 12, 2019
1 parent 7d60dc8 commit e0e1023
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 86 deletions.
75 changes: 37 additions & 38 deletions book/06-concurrency/sections/02-locks.asc
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,42 @@

=== Locks

.Objetivo
.Objective
--------------------------------------------------
Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks and java.util.concurrent.atomic packages to support lock-free thread-safe programming on single variables
-
Usar classes dos tipos Lock, ReadWriteLock, e ReentrantLock dos pacotes java.util.concurrent.locks e java.util.concurrent.atomic para suportar programa莽茫o sem bloqueio e multi-thread em vari谩veis 煤nicas
--------------------------------------------------

As classes e interfaces `Lock`, `ReadWriteLock` e `ReentrantLock` permitem obter diferentes tipos de _Locks_ (em tradu莽茫o livre: bloqueios ou travas). Esses _Locks_ s茫o utilizados para que um n煤mero limitado de _threads_ tenham acesso a mesma vari谩vel em um determinado momento, ou para que apenas uma delas possa alterar seu valor.
The `Lock`, `ReadWriteLock` and `ReentrantLock` classes and interfaces allow for different types of _Locks_. These _Locks_ are used so that a limited number of _threads_ have access to the same variable at any given time, or so that only one of them can change its value.

Nesta se莽茫o ser茫o apresentados exemplos utilizando essas classes e interfaces. Assim como em outras se莽玫es deste cap铆tulo, os exemplos podem ser grandes quando for necess谩rio a cria莽茫o de __threads__. Dedique um tempo maior para entend锚-los completamente.
In this section examples will be presented using these classes and interfaces. As in other sections of this chapter, examples can be large when creating _threads_ is required. Take more time to fully understand them.

==== Reentrant Lock

. 脡 poss铆vel adquirir um _Lock_ utilizando a classe ``ReentrantLock``.
. You can get a _Lock_ using the `ReentrantLock` class.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReentrantLock.java
----
include::{section-java-package}/locks/Locks_ReentrantLock.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
ABC
----
+
Perceba que o _lock_ 茅 removido dentro de um bloco ``finally``. Isso garante que uma _thread_ n茫o ir谩 ficar com um _lock_ indeterminadamente.
Note that _lock_ is removed within a `finally` block. This ensures that a _thread_ will not have an _lock_ indefinitely.

. Chamar o m茅todo unlock sem ter obtido um lock anteriormente ir谩 lan莽ar uma exce莽茫o.
. Calling the unlock method without previously locking will throw an exception.
+
[source,java,indent=0]
.{java-package}/locks/Locks_UnlockWithoutLock.java
----
include::{section-java-package}/locks/Locks_UnlockWithoutLock.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
ABC
Expand All @@ -51,123 +49,124 @@ Exception in thread "main" java.lang.IllegalMonitorStateException
at org.j6toj8.concurrency.locks.Locks_UnlockWithoutLock.main(Locks_UnlockWithoutLock.java:14)
----

. 脡 poss铆vel tentar obter um _lock_ imediatamente utilizando o m茅todo ``tryLock``.
. You can try to get a _lock_ immediately using the `tryLock` method.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLock.java
----
include::{section-java-package}/locks/Locks_TryLock.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
ABC
----

. Tamb茅m 茅 poss铆vel tentar obter um _lock_ definindo um tempo de espera m谩ximo.
. You can also try to get a _lock_ by setting a maximum wait time.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLockTimeout.java
----
include::{section-java-package}/locks/Locks_TryLockTimeout.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
ABC
----

. Em um cen谩rio com v谩rias __threads__, 茅 poss铆vel que apenas uma delas consiga obter um __lock__.
. In a scenario with multiple _threads_, only one of them may be able to obtain a _lock_.
+
[source,java,indent=0]
.{java-package}/locks/Locks_TryLockMultithread.java
----
include::{section-java-package}/locks/Locks_TryLockMultithread.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
Thread-0: Conseguiu o Lock
Thread-2: Conseguiu o Lock
Thread-0: Got the Lock
Thread-2: Got the Lock
----
+
Nesta execu莽茫o com 3 __threads__, apenas duas conseguiram obter o _lock_ imediatamente e imprimir no console. Por茅m o resultado 茅 imprevis铆vel. Podem existir execu莽玫es onde todas obter茫o o __lock__, e outras em que apenas uma thread conseguir谩.
In this 3 _threads_ run, only two were able to get _lock_ immediately and print to the console. But the result is unpredictable. There may be executions where all will get the _lock_, and others where only one thread will succeed.

. Uma _thread_ pode obter mais de um _lock_ no mesmo objeto ``Lock``, mas deve desfazer o _lock_ m煤ltiplas vezes tamb茅m.
. A _thread_ can get more than one _lock_ on the same `Lock` object, but must undo _lock_ multiple times as well.
+
[source,java,indent=0]
.{java-package}/locks/Locks_LockTwice.java
----
include::{section-java-package}/locks/Locks_LockTwice.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
ABC
----
+
Como a _thread_ chamou `lock` duas vezes, caso ela n茫o houvesse chamado `unlock` duas vezes, outra _thread_ n茫o seria capaz de obter o __lock__.
Since the _thread_ called the `lock` twice, if it had not called `unlock` twice, another _thread_ would not be able to get the _lock_.

. 脡 poss铆vel garantir uma distribui莽茫o mais "justa" de _locks_ passando `true` como argumento para o ``ReentrantLock``.
. You can ensure a more "fair" distribution of _locks_ by passing `true` as an argument to `ReentrantLock`.
+
[source,java,indent=0]
.{java-package}/locks/Locks_Fair.java
----
include::{section-java-package}/locks/Locks_Fair.java[tag=code]
----
+
Ao passar o argumento ``true``, quando v谩rias _threads_ estiverem esperando pelo mesmo __lock__, ele ser谩 dado 脿quela _thread_ que est谩 aguardando a mais tempo.
When passing the `true` argument, when multiple _threads_ are waiting for the same _lock_, it will be given to that _thread_ that has been waiting the longest.

==== ReentrantReadWriteLock

. 脡 poss铆vel separar _locks_ de leitura e escrita utilizando a classe ``ReadWriteLock``. _Locks_ de leitura podem ser obtidos por m煤ltiplas _threads_, por茅m _locks_ de escrita n茫o.
. You can separate read and write _locks_ using the `ReadWriteLock` class. Read _Locks_ can be obtained by multiple _threads_, but write _locks_ cannot.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReadWriteLock.java
----
include::{section-java-package}/locks/Locks_ReadWriteLock.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
Thread-0: Conseguiu o Lock de leitura
Thread-2: Conseguiu o Lock de leitura
Thread-1: Conseguiu o Lock de leitura
Thread-1: Conseguiu o Lock de escrita
Thread-0: Got the read Lock
Thread-2: Got the read Lock
Thread-1: Got the read Lock
Thread-1: Got the write Lock
----
+
Perceba que todas as _threads_ conseguiram obter o _lock_ de leitura, por茅m apenas uma conseguiu obter o _lock_ de escrita.
Note that all _threads_ were able to get read _lock_, but only one could get write _lock_.

. Se uma _thread_ j谩 possuir o _lock_ de escrita, outras n茫o conseguir茫o obter nem mesmo o _lock_ de leitura.
. If one _thread_ already has write _lock_, others will not be able to get even read _lock_.
+
[source,java,indent=0]
.{java-package}/locks/Locks_ReadWriteLockInverted.java
----
include::{section-java-package}/locks/Locks_ReadWriteLockInverted.java[tag=code]
----
+
.Sa铆da no console
.console output
[source,console]
----
Thread-0: Conseguiu o Lock de escrita
Thread-0: Conseguiu o Lock de leitura
Thread-0: Got the write Lock
Thread-0: Got the read Lock
----
+
Perceba que neste exemplo o _lock_ de escrita est谩 sendo obtido *antes* do de leitura, de tal forma que apenas a primeira _thread_ que foi executada conseguiu obter os dois __locks__.
Note that in this example the write _lock_ is being obtained *before* read, so that only the first _thread_ that was executed was able to get both _locks_.

.References
****
* Applying Locks
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Edi莽茫o do Kindle.
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Kindle Edition.
* https://www.baeldung.com/java-concurrent-locks[Guide to java.util.concurrent.Locks.]
* https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/package-summary.html[Package java.util.concurrent.locks.] Java Plataform SE 8.
****
****
4 changes: 2 additions & 2 deletions src/org/j6toj8/concurrency/locks/Locks_Fair.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ public class Locks_Fair {

public static void main(String[] args) {
// tag::code[]
Lock lock = new ReentrantLock(true); // lock "justo"
Lock lock = new ReentrantLock(true); // "fair" lock
try {
lock.lock();
System.out.println("ABC");
} finally {
lock.unlock(); // desfaz o lock
lock.unlock(); // undo the lock
}
// end::code[]
}
Expand Down
4 changes: 2 additions & 2 deletions src/org/j6toj8/concurrency/locks/Locks_LockTwice.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public static void main(String[] args) {
lock.lock();
System.out.println("ABC");
} finally {
lock.unlock(); // desfaz o primeiro lock
lock.unlock(); // desfaz o segundo lock
lock.unlock(); // undo the first lock
lock.unlock(); // undo the second lock
}
// end::code[]
}
Expand Down
22 changes: 11 additions & 11 deletions src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
public class Locks_ReadWriteLock {

// tag::code[]
static class Acao implements Runnable {
static class Action implements Runnable {

private ReadWriteLock lock;

public Acao(ReadWriteLock reentrantLock) {
public Action(ReadWriteLock reentrantLock) {
this.lock = reentrantLock;
}

Expand All @@ -20,7 +20,7 @@ public void run() {
Lock readLock = lock.readLock();
if (readLock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura");
System.out.println(Thread.currentThread().getName() + ": Got the read Lock");
} finally {
readLock.unlock();
}
Expand All @@ -29,7 +29,7 @@ public void run() {
Lock writeLock = lock.writeLock();
if (writeLock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita");
System.out.println(Thread.currentThread().getName() + ": Got the write Lock");
} finally {
writeLock.unlock();
}
Expand All @@ -39,13 +39,13 @@ public void run() {

public static void main(String[] args) {
ReadWriteLock lock = new ReentrantReadWriteLock();
// Cria莽茫o das threads
Thread thread1 = new Thread(new Acao(lock));
Thread thread2 = new Thread(new Acao(lock));
Thread thread3 = new Thread(new Acao(lock));
// Execu莽茫o das threads

// Thread creation
Thread thread1 = new Thread(new Action(lock));
Thread thread2 = new Thread(new Action(lock));
Thread thread3 = new Thread(new Action(lock));

// Thread Execution
thread1.start();
thread2.start();
thread3.start();
Expand Down
22 changes: 11 additions & 11 deletions src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
public class Locks_ReadWriteLockInverted {

// tag::code[]
static class Acao implements Runnable {
static class Action implements Runnable {

private ReadWriteLock lock;

public Acao(ReadWriteLock reentrantLock) {
public Action(ReadWriteLock reentrantLock) {
this.lock = reentrantLock;
}

Expand All @@ -20,7 +20,7 @@ public void run() {
Lock writeLock = lock.writeLock();
if (writeLock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita");
System.out.println(Thread.currentThread().getName() + ": Got the read Lock");
} finally {
writeLock.unlock();
}
Expand All @@ -29,7 +29,7 @@ public void run() {
Lock readLock = lock.readLock();
if (readLock.tryLock()) {
try {
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura");
System.out.println(Thread.currentThread().getName() + ": Got the write Lock");
} finally {
readLock.unlock();
}
Expand All @@ -39,13 +39,13 @@ public void run() {

public static void main(String[] args) {
ReadWriteLock lock = new ReentrantReadWriteLock();
// Cria莽茫o das threads
Thread thread1 = new Thread(new Acao(lock));
Thread thread2 = new Thread(new Acao(lock));
Thread thread3 = new Thread(new Acao(lock));
// Execu莽茫o das threads

// Thread creation
Thread thread1 = new Thread(new Action(lock));
Thread thread2 = new Thread(new Action(lock));
Thread thread3 = new Thread(new Action(lock));

// Thread Execution
thread1.start();
thread2.start();
thread3.start();
Expand Down
4 changes: 2 additions & 2 deletions src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ public static void main(String[] args) {
// tag::code[]
Lock lock = new ReentrantLock();
try {
lock.lock(); // apenas uma thread obt茅m o lock por vez
lock.lock(); // only one thread gets lock at a time
System.out.println("ABC");
} finally {
lock.unlock(); // desfaz o lock
lock.unlock(); // undo the lock
}
// end::code[]
}
Expand Down
6 changes: 3 additions & 3 deletions src/org/j6toj8/concurrency/locks/Locks_TryLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ public class Locks_TryLock {
public static void main(String[] args) {
// tag::code[]
Lock lock = new ReentrantLock();
boolean temLock = lock.tryLock();
boolean hasLock = lock.tryLock();

if (temLock) {
if (hasLock) {
try {
System.out.println("ABC");
} finally {
lock.unlock(); // desfaz o lock
lock.unlock(); // undo the lock
}
} else {
System.out.println("DEF");
Expand Down
Loading

0 comments on commit e0e1023

Please sign in to comment.