本文主要根据《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();
}
}
(只含关键代码)