Commit 151887db authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch15b] Using CopyOnWriteArrayList to fix reader code

parent faef4859
Loading
Loading
Loading
Loading
+5 −3
Changes for src/main/java/ch15/LotsOfReaders.java: 5 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -2,16 +2,17 @@ package ch15;

import java.time.LocalDateTime;
import java.time.format.FormatStyle;
import java.util.ArrayList;
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 static java.time.format.DateTimeFormatter.ofLocalizedTime;

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

  private static void printChatHistory(String name, List<Chat> chatHistory) {