Skip to content

Commit e0e1023

Browse files
committed
feat(concurrency): 🎸 locks, translated
Refers: #8
1 parent 7d60dc8 commit e0e1023

File tree

10 files changed

+85
-86
lines changed

10 files changed

+85
-86
lines changed

book/06-concurrency/sections/02-locks.asc

Lines changed: 37 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,42 @@
33

44
=== Locks
55

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

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

15-
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.
13+
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.
1614

1715
==== Reentrant Lock
1816

19-
. É possível adquirir um _Lock_ utilizando a classe ``ReentrantLock``.
17+
. You can get a _Lock_ using the `ReentrantLock` class.
2018
+
2119
[source,java,indent=0]
2220
.{java-package}/locks/Locks_ReentrantLock.java
2321
----
2422
include::{section-java-package}/locks/Locks_ReentrantLock.java[tag=code]
2523
----
2624
+
27-
.Saída no console
25+
.console output
2826
[source,console]
2927
----
3028
ABC
3129
----
3230
+
33-
Perceba que o _lock_ é removido dentro de um bloco ``finally``. Isso garante que uma _thread_ não irá ficar com um _lock_ indeterminadamente.
31+
Note that _lock_ is removed within a `finally` block. This ensures that a _thread_ will not have an _lock_ indefinitely.
3432

35-
. Chamar o método unlock sem ter obtido um lock anteriormente irá lançar uma exceção.
33+
. Calling the unlock method without previously locking will throw an exception.
3634
+
3735
[source,java,indent=0]
3836
.{java-package}/locks/Locks_UnlockWithoutLock.java
3937
----
4038
include::{section-java-package}/locks/Locks_UnlockWithoutLock.java[tag=code]
4139
----
4240
+
43-
.Saída no console
41+
.console output
4442
[source,console]
4543
----
4644
ABC
@@ -51,123 +49,124 @@ Exception in thread "main" java.lang.IllegalMonitorStateException
5149
at org.j6toj8.concurrency.locks.Locks_UnlockWithoutLock.main(Locks_UnlockWithoutLock.java:14)
5250
----
5351

54-
. É possível tentar obter um _lock_ imediatamente utilizando o método ``tryLock``.
52+
. You can try to get a _lock_ immediately using the `tryLock` method.
5553
+
5654
[source,java,indent=0]
5755
.{java-package}/locks/Locks_TryLock.java
5856
----
5957
include::{section-java-package}/locks/Locks_TryLock.java[tag=code]
6058
----
6159
+
62-
.Saída no console
60+
.console output
6361
[source,console]
6462
----
6563
ABC
6664
----
6765

68-
. Também é possível tentar obter um _lock_ definindo um tempo de espera máximo.
66+
. You can also try to get a _lock_ by setting a maximum wait time.
6967
+
7068
[source,java,indent=0]
7169
.{java-package}/locks/Locks_TryLockTimeout.java
7270
----
7371
include::{section-java-package}/locks/Locks_TryLockTimeout.java[tag=code]
7472
----
7573
+
76-
.Saída no console
74+
.console output
7775
[source,console]
7876
----
7977
ABC
8078
----
8179

82-
. Em um cenário com várias __threads__, é possível que apenas uma delas consiga obter um __lock__.
80+
. In a scenario with multiple _threads_, only one of them may be able to obtain a _lock_.
8381
+
8482
[source,java,indent=0]
8583
.{java-package}/locks/Locks_TryLockMultithread.java
8684
----
8785
include::{section-java-package}/locks/Locks_TryLockMultithread.java[tag=code]
8886
----
8987
+
90-
.Saída no console
88+
.console output
9189
[source,console]
9290
----
93-
Thread-0: Conseguiu o Lock
94-
Thread-2: Conseguiu o Lock
91+
Thread-0: Got the Lock
92+
Thread-2: Got the Lock
9593
----
9694
+
97-
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á.
95+
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.
9896

99-
. Uma _thread_ pode obter mais de um _lock_ no mesmo objeto ``Lock``, mas deve desfazer o _lock_ múltiplas vezes também.
97+
. A _thread_ can get more than one _lock_ on the same `Lock` object, but must undo _lock_ multiple times as well.
10098
+
10199
[source,java,indent=0]
102100
.{java-package}/locks/Locks_LockTwice.java
103101
----
104102
include::{section-java-package}/locks/Locks_LockTwice.java[tag=code]
105103
----
106104
+
107-
.Saída no console
105+
.console output
108106
[source,console]
109107
----
110108
ABC
111109
----
112110
+
113-
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__.
111+
Since the _thread_ called the `lock` twice, if it had not called `unlock` twice, another _thread_ would not be able to get the _lock_.
114112

115-
. É possível garantir uma distribuição mais "justa" de _locks_ passando `true` como argumento para o ``ReentrantLock``.
113+
. You can ensure a more "fair" distribution of _locks_ by passing `true` as an argument to `ReentrantLock`.
116114
+
117115
[source,java,indent=0]
118116
.{java-package}/locks/Locks_Fair.java
119117
----
120118
include::{section-java-package}/locks/Locks_Fair.java[tag=code]
121119
----
122120
+
123-
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.
121+
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.
124122

125123
==== ReentrantReadWriteLock
126124

127-
. É 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.
125+
. You can separate read and write _locks_ using the `ReadWriteLock` class. Read _Locks_ can be obtained by multiple _threads_, but write _locks_ cannot.
128126
+
129127
[source,java,indent=0]
130128
.{java-package}/locks/Locks_ReadWriteLock.java
131129
----
132130
include::{section-java-package}/locks/Locks_ReadWriteLock.java[tag=code]
133131
----
134132
+
135-
.Saída no console
133+
.console output
136134
[source,console]
137135
----
138-
Thread-0: Conseguiu o Lock de leitura
139-
Thread-2: Conseguiu o Lock de leitura
140-
Thread-1: Conseguiu o Lock de leitura
141-
Thread-1: Conseguiu o Lock de escrita
136+
Thread-0: Got the read Lock
137+
Thread-2: Got the read Lock
138+
Thread-1: Got the read Lock
139+
Thread-1: Got the write Lock
142140
----
143141
+
144-
Perceba que todas as _threads_ conseguiram obter o _lock_ de leitura, porém apenas uma conseguiu obter o _lock_ de escrita.
142+
Note that all _threads_ were able to get read _lock_, but only one could get write _lock_.
145143

146-
. Se uma _thread_ já possuir o _lock_ de escrita, outras não conseguirão obter nem mesmo o _lock_ de leitura.
144+
. If one _thread_ already has write _lock_, others will not be able to get even read _lock_.
147145
+
148146
[source,java,indent=0]
149147
.{java-package}/locks/Locks_ReadWriteLockInverted.java
150148
----
151149
include::{section-java-package}/locks/Locks_ReadWriteLockInverted.java[tag=code]
152150
----
153151
+
154-
.Saída no console
152+
.console output
155153
[source,console]
156154
----
157-
Thread-0: Conseguiu o Lock de escrita
158-
Thread-0: Conseguiu o Lock de leitura
155+
Thread-0: Got the write Lock
156+
Thread-0: Got the read Lock
159157
----
160158
+
161-
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__.
159+
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_.
162160

161+
.References
163162
****
164163
165164
* Applying Locks
166165
+
167-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Edição do Kindle.
166+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 607). Wiley. Kindle Edition.
168167
169168
* https://www.baeldung.com/java-concurrent-locks[Guide to java.util.concurrent.Locks.]
170169
171170
* https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/package-summary.html[Package java.util.concurrent.locks.] Java Plataform SE 8.
172171
173-
****
172+
****

src/org/j6toj8/concurrency/locks/Locks_Fair.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ public class Locks_Fair {
77

88
public static void main(String[] args) {
99
// tag::code[]
10-
Lock lock = new ReentrantLock(true); // lock "justo"
10+
Lock lock = new ReentrantLock(true); // "fair" lock
1111
try {
1212
lock.lock();
1313
System.out.println("ABC");
1414
} finally {
15-
lock.unlock(); // desfaz o lock
15+
lock.unlock(); // undo the lock
1616
}
1717
// end::code[]
1818
}

src/org/j6toj8/concurrency/locks/Locks_LockTwice.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ public static void main(String[] args) {
1313
lock.lock();
1414
System.out.println("ABC");
1515
} finally {
16-
lock.unlock(); // desfaz o primeiro lock
17-
lock.unlock(); // desfaz o segundo lock
16+
lock.unlock(); // undo the first lock
17+
lock.unlock(); // undo the second lock
1818
}
1919
// end::code[]
2020
}

src/org/j6toj8/concurrency/locks/Locks_ReadWriteLock.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
public class Locks_ReadWriteLock {
88

99
// tag::code[]
10-
static class Acao implements Runnable {
10+
static class Action implements Runnable {
1111

1212
private ReadWriteLock lock;
1313

14-
public Acao(ReadWriteLock reentrantLock) {
14+
public Action(ReadWriteLock reentrantLock) {
1515
this.lock = reentrantLock;
1616
}
1717

@@ -20,7 +20,7 @@ public void run() {
2020
Lock readLock = lock.readLock();
2121
if (readLock.tryLock()) {
2222
try {
23-
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura");
23+
System.out.println(Thread.currentThread().getName() + ": Got the read Lock");
2424
} finally {
2525
readLock.unlock();
2626
}
@@ -29,7 +29,7 @@ public void run() {
2929
Lock writeLock = lock.writeLock();
3030
if (writeLock.tryLock()) {
3131
try {
32-
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita");
32+
System.out.println(Thread.currentThread().getName() + ": Got the write Lock");
3333
} finally {
3434
writeLock.unlock();
3535
}
@@ -39,13 +39,13 @@ public void run() {
3939

4040
public static void main(String[] args) {
4141
ReadWriteLock lock = new ReentrantReadWriteLock();
42-
43-
// Criação das threads
44-
Thread thread1 = new Thread(new Acao(lock));
45-
Thread thread2 = new Thread(new Acao(lock));
46-
Thread thread3 = new Thread(new Acao(lock));
47-
48-
// Execução das threads
42+
43+
// Thread creation
44+
Thread thread1 = new Thread(new Action(lock));
45+
Thread thread2 = new Thread(new Action(lock));
46+
Thread thread3 = new Thread(new Action(lock));
47+
48+
// Thread Execution
4949
thread1.start();
5050
thread2.start();
5151
thread3.start();

src/org/j6toj8/concurrency/locks/Locks_ReadWriteLockInverted.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
public class Locks_ReadWriteLockInverted {
88

99
// tag::code[]
10-
static class Acao implements Runnable {
10+
static class Action implements Runnable {
1111

1212
private ReadWriteLock lock;
1313

14-
public Acao(ReadWriteLock reentrantLock) {
14+
public Action(ReadWriteLock reentrantLock) {
1515
this.lock = reentrantLock;
1616
}
1717

@@ -20,7 +20,7 @@ public void run() {
2020
Lock writeLock = lock.writeLock();
2121
if (writeLock.tryLock()) {
2222
try {
23-
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de escrita");
23+
System.out.println(Thread.currentThread().getName() + ": Got the read Lock");
2424
} finally {
2525
writeLock.unlock();
2626
}
@@ -29,7 +29,7 @@ public void run() {
2929
Lock readLock = lock.readLock();
3030
if (readLock.tryLock()) {
3131
try {
32-
System.out.println(Thread.currentThread().getName() + ": Conseguiu o Lock de leitura");
32+
System.out.println(Thread.currentThread().getName() + ": Got the write Lock");
3333
} finally {
3434
readLock.unlock();
3535
}
@@ -39,13 +39,13 @@ public void run() {
3939

4040
public static void main(String[] args) {
4141
ReadWriteLock lock = new ReentrantReadWriteLock();
42-
43-
// Criação das threads
44-
Thread thread1 = new Thread(new Acao(lock));
45-
Thread thread2 = new Thread(new Acao(lock));
46-
Thread thread3 = new Thread(new Acao(lock));
47-
48-
// Execução das threads
42+
43+
// Thread creation
44+
Thread thread1 = new Thread(new Action(lock));
45+
Thread thread2 = new Thread(new Action(lock));
46+
Thread thread3 = new Thread(new Action(lock));
47+
48+
// Thread Execution
4949
thread1.start();
5050
thread2.start();
5151
thread3.start();

src/org/j6toj8/concurrency/locks/Locks_ReentrantLock.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ public static void main(String[] args) {
99
// tag::code[]
1010
Lock lock = new ReentrantLock();
1111
try {
12-
lock.lock(); // apenas uma thread obtém o lock por vez
12+
lock.lock(); // only one thread gets lock at a time
1313
System.out.println("ABC");
1414
} finally {
15-
lock.unlock(); // desfaz o lock
15+
lock.unlock(); // undo the lock
1616
}
1717
// end::code[]
1818
}

src/org/j6toj8/concurrency/locks/Locks_TryLock.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@ public class Locks_TryLock {
88
public static void main(String[] args) {
99
// tag::code[]
1010
Lock lock = new ReentrantLock();
11-
boolean temLock = lock.tryLock();
11+
boolean hasLock = lock.tryLock();
1212

13-
if (temLock) {
13+
if (hasLock) {
1414
try {
1515
System.out.println("ABC");
1616
} finally {
17-
lock.unlock(); // desfaz o lock
17+
lock.unlock(); // undo the lock
1818
}
1919
} else {
2020
System.out.println("DEF");

0 commit comments

Comments
 (0)