Java 7新機能(四)同時5 CopyOnWriteArrayListオブジェクト


本文は主に『Javaプログラマー修練の道』に基づいて整理したコードノートの断片
CopyOnWriteArrayListオブジェクト書き込み時にコピーを追加し、スナップショットをすばやく一致させる【リーダーごとのパフォーマンス、自己一致スナップショット】
(不完全な同期、重要でないタスク、修正回数と読み取り回数の差が大きい)
public class MicroBlogTimeline {
  private final CopyOnWriteArrayList<Update> updates;
  // ,   【 , 】 ( , , )
  
  private final Lock lock;
  private final String name;
  private Iterator<Update> it;

  public MicroBlogTimeline(String name_) {
    name = name_;
    updates = new CopyOnWriteArrayList<>();
    lock = new ReentrantLock();
  }

  MicroBlogTimeline(String name_, CopyOnWriteArrayList<Update> l_, Lock lock_) {
    name = name_;
    updates = l_;
    lock = lock_;
  }

  public void addUpdate(Update update_) {
    updates.add(update_);
  }

  public void prep() {
    it = updates.iterator();
  }

  public void printTimeline() {
    lock.lock();
    try {
      if (it != null) {
        System.out.print(name + ": ");
        while (it.hasNext()) {
          Update s = it.next();
          System.out.print(s + ", ");
        }
        System.out.println();
      }
    } finally {
      lock.unlock();
    }
  }
}
public class CopyOnWriteExampleMain {

  public static void main(String[] a) {
    final CountDownLatch firstLatch = new CountDownLatch(1);
    final CountDownLatch secondLatch = new CountDownLatch(1);
    final Update.Builder ub = new Update.Builder();

    final CopyOnWriteArrayList<Update> l = new CopyOnWriteArrayList<>();
    l.add(ub.author(new Author("Ben")).updateText("I like pie").build());
    l.add(ub.author(new Author("Charles")).updateText("I like ham on rye")
        .build());

    Lock lock = new ReentrantLock();
    final MicroBlogTimeline tl1 = new MicroBlogTimeline("TL1", l, lock);
    final MicroBlogTimeline tl2 = new MicroBlogTimeline("TL2", l, lock);

    Thread t1 = new Thread() {
      public void run() {
        l.add(ub.author(new Author("Jeffrey"))
            .updateText("I like a lot of things").build());
        tl1.prep();
        firstLatch.countDown();
        try {
          secondLatch.await();
        } catch (InterruptedException e) {
        }
        tl1.printTimeline();
      }
    };

    Thread t2 = new Thread() {
      public void run() {
        try {
          firstLatch.await();
          l.add(ub.author(new Author("Gavin")).updateText("I like otters")
              .build());
          tl2.prep();
          secondLatch.countDown();
        } catch (InterruptedException e) {
        }
        tl2.printTimeline();
      }
    };
    t1.start();
    t2.start();
  }

}

(キーコードのみ含む)