Commit af9bf7da authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15b] Even simpler concurrent readers example

parent 463da14c
Loading
Loading
Loading
Loading
+7 −15
Changes for src/main/java/ch15b/ConcurrentReaders.java: 7 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -2,35 +2,27 @@ package ch15b;

import java.time.LocalDateTime;
import java.time.format.FormatStyle;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.*;
import java.util.concurrent.*;

import static java.time.format.DateTimeFormatter.ofLocalizedTime;

public class LotsOfReaders {
public class ConcurrentReaders {
  public static void main(String[] args) throws InterruptedException {
    List<Chat> chatHistory = new CopyOnWriteArrayList<>();
    List<Chat> chatHistory = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 5; i++) {
      executor.execute(() -> chatHistory.add(new Chat("Hi there!")));
      executor.execute(() -> printChatHistory("Reader 1", chatHistory));
      executor.execute(() -> printChatHistory("Reader 2", chatHistory));
      executor.execute(() -> System.out.println(chatHistory));
      executor.execute(() -> System.out.println(chatHistory));
    }
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.MINUTES);
  }

  private static void printChatHistory(String name, List<Chat> chatHistory) {
    for (Chat chat : chatHistory) {
      System.out.println(name + " read: " + chat);
    }
  }
}

class Chat {
final class Chat {
  private final String message;
  private final LocalDateTime timestamp;