2015-04-20 15:36:01 -07:00
|
|
|
|
//: concurrency/ExplicitCriticalSection.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-29 13:56:17 -07:00
|
|
|
|
// {ThrowsException} on a multiprocessor machine
|
2015-04-20 15:36:01 -07:00
|
|
|
|
// Using explicit Lock objects to create critical sections.
|
|
|
|
|
package concurrency;
|
|
|
|
|
import java.util.concurrent.locks.*;
|
|
|
|
|
|
|
|
|
|
// Synchronize the entire method:
|
|
|
|
|
class ExplicitPairManager1 extends PairManager {
|
|
|
|
|
private Lock lock = new ReentrantLock();
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-29 13:56:17 -07:00
|
|
|
|
public void increment() {
|
2015-04-20 15:36:01 -07:00
|
|
|
|
lock.lock();
|
|
|
|
|
try {
|
|
|
|
|
p.incrementX();
|
|
|
|
|
p.incrementY();
|
|
|
|
|
store(getPair());
|
|
|
|
|
} finally {
|
|
|
|
|
lock.unlock();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Use a critical section:
|
|
|
|
|
class ExplicitPairManager2 extends PairManager {
|
|
|
|
|
private Lock lock = new ReentrantLock();
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public void increment() {
|
|
|
|
|
Pair temp;
|
|
|
|
|
lock.lock();
|
|
|
|
|
try {
|
|
|
|
|
p.incrementX();
|
|
|
|
|
p.incrementY();
|
|
|
|
|
temp = getPair();
|
|
|
|
|
} finally {
|
|
|
|
|
lock.unlock();
|
|
|
|
|
}
|
2015-05-18 23:05:20 -07:00
|
|
|
|
store(temp);
|
2015-04-20 15:36:01 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class ExplicitCriticalSection {
|
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
|
|
|
PairManager
|
|
|
|
|
pman1 = new ExplicitPairManager1(),
|
|
|
|
|
pman2 = new ExplicitPairManager2();
|
|
|
|
|
CriticalSection.testApproaches(pman1, pman2);
|
|
|
|
|
}
|
2015-05-05 11:20:13 -07:00
|
|
|
|
} ///:~
|