Skip to content

Commit

Permalink
feat(concurrency): 🎸 execute tasks, translated
Browse files Browse the repository at this point in the history
Refers: #8
  • Loading branch information
rcmoutinho committed Sep 12, 2019
1 parent e0e1023 commit ab329fd
Show file tree
Hide file tree
Showing 18 changed files with 240 additions and 242 deletions.
278 changes: 138 additions & 140 deletions book/06-concurrency/sections/03-execute-tasks.asc

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ public static void main(String[] args) {
// tag::code[]
ScheduledExecutorService executor = null;
try {
executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread
System.out.println("Agora: " + LocalTime.now()); // imprime a hora atual
executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler
System.out.println("Now: " + LocalTime.now()); // print the current time

executor.schedule(() -> System.out.println("Execução: " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution: " + LocalTime.now()), 3, TimeUnit.SECONDS);
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ public static void main(String[] args) {
// tag::code[]
ScheduledExecutorService executor = null;
try {
executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread
System.out.println("Antes do agendamento: " + LocalTime.now());
ScheduledFuture<String> retorno = executor.schedule(() -> "Execução: " + LocalTime.now(), 3, TimeUnit.SECONDS);
System.out.println("Depois do agendamento: " + LocalTime.now());
executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler
System.out.println("Before Scheduling: " + LocalTime.now());
ScheduledFuture<String> futureReturn = executor.schedule(() -> "Execution: " + LocalTime.now(), 3, TimeUnit.SECONDS);
System.out.println("After Scheduling: " + LocalTime.now());

System.out.println(retorno.get()); // fica parado aqui esperando o retorno
System.out.println("Depois da execução: " + LocalTime.now());
System.out.println(futureReturn.get()); // stands here waiting for the return
System.out.println("After execution: " + LocalTime.now());
} catch (InterruptedException | ExecutionException e) {
System.out.println("Erro ao fazer .get()");
System.out.println("Error doing .get()");
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ public class Schedule_SingleThreadFixedDelay {
public static void main(String[] args) {
ScheduledExecutorService executor = null;
try {
executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread
System.out.println("Antes do agendamento: " + LocalTime.now()); // imprime a hora atual
executor.scheduleWithFixedDelay(() -> System.out.println("Execução: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS);
System.out.println("Após do agendamento: " + LocalTime.now()); // imprime a hora atual
sleep(); // aguarda um tempo para ser possível enxergar as execuções
System.out.println("Após o sleep de 10 segundos: " + LocalTime.now()); // imprime a hora atual
executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler
System.out.println("Before Scheduling: " + LocalTime.now()); // print the current time
executor.scheduleWithFixedDelay(() -> System.out.println("Execution: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS);
System.out.println("After Scheduling: " + LocalTime.now()); // print the current time
sleep(); // waits a while to be able to see the executions
System.out.println("After 10 seconds sleep: " + LocalTime.now()); // print the current time
} finally {
if (executor != null) {
System.out.println("Invocando shutdown no executor.");
System.out.println("Invoking shutdown on executor.");
executor.shutdown();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ public class Schedule_SingleThreadFixedRate {
public static void main(String[] args) {
ScheduledExecutorService executor = null;
try {
executor = Executors.newSingleThreadScheduledExecutor(); // executor de agendamento com uma única thread
System.out.println("Antes do agendamento: " + LocalTime.now()); // imprime a hora atual
executor.scheduleAtFixedRate(() -> System.out.println("Execução: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS);
System.out.println("Após do agendamento: " + LocalTime.now()); // imprime a hora atual
sleep(); // aguarda um tempo para ser possível enxergar as execuções
System.out.println("Após o sleep de 10 segundos: " + LocalTime.now()); // imprime a hora atual
executor = Executors.newSingleThreadScheduledExecutor(); // single thread scheduler
System.out.println("Before Scheduling: " + LocalTime.now()); // print the current time
executor.scheduleAtFixedRate(() -> System.out.println("Execution: " + LocalTime.now()), 3, 1, TimeUnit.SECONDS);
System.out.println("After Scheduling: " + LocalTime.now()); // print the current time
sleep(); // waits a while to be able to see the executions
System.out.println("After 10 seconds sleep: " + LocalTime.now()); // print the current time
} finally {
if (executor != null) {
System.out.println("Invocando shutdown no executor.");
System.out.println("Invoking shutdown on executor.");
executor.shutdown();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ public static void main(String[] args) {
// tag::code[]
ExecutorService executor = null;
try {
executor = Executors.newCachedThreadPool(); // executor com cache de threads
executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 4 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 5 - Thread do Executor: " + Thread.currentThread().getName()));
executor = Executors.newCachedThreadPool(); // thread cached executor
executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 4 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 5 - Executor Thread: " + Thread.currentThread().getName()));
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ public static void main(String[] args) {
// tag::code[]
ExecutorService executor = null;
try {
executor = Executors.newFixedThreadPool(2); // executor com duas threads
executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 4 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 5 - Thread do Executor: " + Thread.currentThread().getName()));
executor = Executors.newFixedThreadPool(2); // two thread executor
executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 4 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 5 - Executor Thread: " + Thread.currentThread().getName()));
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ public static void main(String[] args) {
// tag::code[]
ScheduledExecutorService executor = null;
try {
executor = Executors.newScheduledThreadPool(2); // executor de agendamento com duas threads
System.out.println("Agora: " + LocalTime.now()); // imprime a hora atual
executor = Executors.newScheduledThreadPool(2); // two thread scheduling executor
System.out.println("Now: " + LocalTime.now()); // print the current time

executor.schedule(() -> System.out.println("Execução 1: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execução 2: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execução 3: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execução 4: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execução 5: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution 1: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution 2: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution 3: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution 4: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
executor.schedule(() -> System.out.println("Execution 5: " + Thread.currentThread().getName() + " - " + LocalTime.now()), 3, TimeUnit.SECONDS);
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ public static void main(String[] args) {
try {
executor = Executors.newSingleThreadExecutor();

// tarefa sem retorno, instância de Runnable
// task without return, instance of Runnable
executor.submit(() -> System.out.println("Runnable"));

// tarefa com retorno, instância de Callable
// task with return, instance of Callable
executor.submit(() -> "Callable");
// tarefa que lança uma Exception deve ser Callable, logo deve ter retorno

// task that throws an Exception must be Callable, then needs to return
executor.submit(() -> {Thread.sleep(1); return "Callable";});

// tarefa que lança uma Exception, mas não declara retorno
// NÃO COMPILA pois é interpretada como Runnable
// task that throws an Exception, but declares no return
// NOT COMPILING as it is interpreted as Runnable
executor.submit(() -> Thread.sleep(1));

} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ public static void main(String[] args) {
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName()));
System.out.println("Thread Principal: " + Thread.currentThread().getName());
executor.execute(() -> System.out.println("Executor Thread: " + Thread.currentThread().getName()));
System.out.println("Main Thread: " + Thread.currentThread().getName());
} finally {
if (executor != null) {
executor.shutdownNow(); // TENTA encerrar todas as threads imediatamente
executor.shutdownNow(); // TRIES to shut down all threads immediately
}
}
// end::code[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public static void main(String[] args) {
// tag::code[]
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor(); // executor com uma única thread
executor.execute(() -> System.out.println("Thread do Executor: " + Thread.currentThread().getName()));
System.out.println("Thread Principal: " + Thread.currentThread().getName());
executor = Executors.newSingleThreadExecutor(); // single thread executor
executor.execute(() -> System.out.println("Executor Thread: " + Thread.currentThread().getName()));
System.out.println("Main Thread: " + Thread.currentThread().getName());
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public static void main(String[] args) {
try {
executor = Executors.newSingleThreadExecutor();

executor.execute(() -> System.out.println("Tarefa 1 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 2 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Tarefa 3 - Thread do Executor: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 1 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 2 - Executor Thread: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 3 - Executor Thread: " + Thread.currentThread().getName()));
} finally {
if (executor != null) {
executor.shutdown();
Expand All @@ -25,11 +25,11 @@ public static void main(String[] args) {

if (executor != null) {
try {
System.out.println("Tarefas finalizadas? " + executor.isTerminated());
System.out.println("Tasks completed? " + executor.isTerminated());
executor.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("Tarefas finalizadas? " + executor.isTerminated());
System.out.println("Tasks completed? " + executor.isTerminated());
} catch (InterruptedException e) {
System.out.println("Erro de interrupção.");
System.out.println("Interruption error.");
}
}
// end::code[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ public static void main(String[] args) {
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();
Future<?> retornoDaTarefa = executor.submit(() -> "String que será retornada");
// O .get() abaixo irá esperar a tarefa finalizar para pegar seu retorno
System.out.println("Retorno da tarefa: " + retornoDaTarefa.get());
Future<?> taskReturn = executor.submit(() -> "String to be returned");

// The .get() below will wait for the task to finish to get its return
System.out.println("Task Return: " + taskReturn.get());
} catch (InterruptedException | ExecutionException e) {
System.out.println("Execução interrompida.");
System.out.println("Execution stopped.");
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ public static void main(String[] args) {
ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();
Future<?> tarefa = executor.submit(() -> System.out.println("Tarefa executando"));
Future<?> task = executor.submit(() -> System.out.println("Task running"));

// verifica se a tarefa está finalizada
System.out.println("Tarefa já finalizada? " + tarefa.isDone());
// tenta cancelar a tarefa
System.out.println("Tentando cancelar a tarefa. Conseguiu? " + tarefa.cancel(true));
// verifica se a tarefa foi cancelada
System.out.println("Tarefa foi cancelada? " + tarefa.isCancelled());
// check if the task is finished
System.out.println("Task already completed? " + task.isDone());

// try to cancel the task
System.out.println("Trying to cancel the task. Got it? " + task.cancel(true));

// check if the task has been canceled
System.out.println("Task was canceled? " + task.isCancelled());
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ public class Tasks_SingleThreadInvokeAll {

public static void main(String[] args) {
// tag::code[]
List<Callable<String>> tarefas = new ArrayList<Callable<String>>();
tarefas.add(() -> "Tarefa 1 executada na thread " + Thread.currentThread().getName());
tarefas.add(() -> "Tarefa 2 executada na thread " + Thread.currentThread().getName());
tarefas.add(() -> "Tarefa 3 executada na thread " + Thread.currentThread().getName());
List<Callable<String>> tasks = new ArrayList<Callable<String>>();
tasks.add(() -> "Task 1 performed on thread" + Thread.currentThread().getName());
tasks.add(() -> "Task 2 performed on thread" + Thread.currentThread().getName());
tasks.add(() -> "Task 3 performed on thread" + Thread.currentThread().getName());

ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();

// invokeAll devolve todos os retornos das tarefas executadas em uma lista
List<Future<String>> retornos = executor.invokeAll(tarefas);
// invokeAll returns all returns of tasks performed in a list
List<Future<String>> returnList = executor.invokeAll(tasks);

for (Future<String> retorno : retornos) {
System.out.println("Retorno da tarefa: " + retorno.get());
for (Future<String> futureReturn : returnList) {
System.out.println("Task Return: " + futureReturn.get());
}
} catch (InterruptedException | ExecutionException e) {
System.out.println("Execução interrompida.");
System.out.println("Execution stopped.");
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,21 @@ public class Tasks_SingleThreadInvokeAny {

public static void main(String[] args) {
// tag::code[]
List<Callable<String>> tarefas = new ArrayList<Callable<String>>();
tarefas.add(() -> "Tarefa 1 executada na thread " + Thread.currentThread().getName());
tarefas.add(() -> "Tarefa 2 executada na thread " + Thread.currentThread().getName());
tarefas.add(() -> "Tarefa 3 executada na thread " + Thread.currentThread().getName());
List<Callable<String>> tasks = new ArrayList<Callable<String>>();
tasks.add(() -> "Task 1 performed on thread" + Thread.currentThread().getName());
tasks.add(() -> "Task 2 performed on thread" + Thread.currentThread().getName());
tasks.add(() -> "Task 3 performed on thread" + Thread.currentThread().getName());

ExecutorService executor = null;
try {
executor = Executors.newSingleThreadExecutor();

// invokeAny devolve apenas uma das tarefas que finalizou e interrompe as outras
String retorno = executor.invokeAny(tarefas);
System.out.println("Retorno da tarefa: " + retorno);
// invokeAny returns only one of the completed tasks and interrupts the others
String singleReturn = executor.invokeAny(tasks);
System.out.println("Task Return: " + singleReturn);

} catch (InterruptedException | ExecutionException e) {
System.out.println("Execução interrompida.");
System.out.println("Execution stopped.");
} finally {
if (executor != null) {
executor.shutdown();
Expand Down
Loading

0 comments on commit ab329fd

Please sign in to comment.