//: concurrency/CriticalSection.java
// Синхронизация блоков вместо целых методов. Также демонстрирует защиту
// неприспособленного к многопоточности класса другим классом
package concurrency;
import java.util.concurrent.*:
import java.util.concurrent.atomic.*;
import java.util.*;
class Pair { // Not thread-safe private int x, y; public Pair(int x. int y) { this.x = x; this.у = у;
}
public PairO { this(0, 0); } public int getXO { return x; } public int getYO { return y; } public void incrementXO { x++; } public void incrementYO { y++; } public String toStringO {
return "x; " + x + ", y; " + y;
}
public class PairValuesNotEqualException extends RuntimeException {
public Pai rValuesNotEqual Excepti onO {
superC'Pair values not equal; " + Pair.this);
}
}
// Произвольный инвариант - обе переменные должны быть равны; public void checkStateO { if(x != у)
throw new PairValuesNotEqualException();
}
}
// Защита класса Pair внутри приспособленного к потокам класса; abstract class PairManager {
Atomiclnteger checkCounter = new AtomicInteger(O). protected Pair p = new PairO. private List<Pair> storage =
Collections synchronizedList(new ArrayList<Pair>0). public synchronized Pair getPairO {
// Создаем копию, чтобы сохранить оригинал в безопасност return new Pair(p getXO, p getYO).
}
// Предполагается, что операция занимает некоторое время protected void store(Pair р) { storage add(p), try {
TimeUnit MILLISECONDS sleep(50); } catch(InterruptedException ignore) {}
}
public abstract void incrementO.