OnJava8-Examples/threads/ExplicitCriticalSection.java

80 lines
2.3 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/ExplicitCriticalSection.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// {ThrowsException} on a multiprocessor machine
2016-01-25 18:05:55 -08:00
// Using explicit Lock objects to create critical sections
2016-07-20 06:32:39 -06:00
// {main: threads.ExplicitCriticalSection}
2016-07-05 14:46:09 -06:00
package threads;
2015-06-15 17:47:35 -07:00
import java.util.concurrent.locks.*;
// Synchronize the entire method:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
@Override
public void increment() {
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();
@Override
public void increment() {
Pair temp;
lock.lock();
try {
p.incrementX();
p.incrementY();
temp = getPair();
} finally {
lock.unlock();
}
store(temp);
}
}
public class ExplicitCriticalSection {
public static void
main(String[] args) throws Exception {
PairManager
pman1 = new ExplicitPairManager1(),
pman2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pman1, pman2);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-22 14:45:35 -06:00
pm1: Pair: x: 10, y: 10 checkCounter = 3504848
pm2: Pair: x: 10, y: 10 checkCounter = 2105413
2015-12-16 13:50:01 -08:00
___[ Error Output ]___
2016-07-22 14:45:35 -06:00
Exception in thread "pool-1-thread-3" Exception in thread
"pool-1-thread-4" threads.Pair$PairValuesNotEqualException:
Pair values not equal: x: 3, y: 2
at threads.Pair.checkState(CriticalSection.java:37)
2015-12-16 13:50:01 -08:00
at
2016-07-22 14:45:35 -06:00
threads.PairChecker.run(CriticalSection.java:111)
2015-12-16 13:50:01 -08:00
at java.util.concurrent.ThreadPoolExecutor.runWorke
r(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.r
un(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
2016-07-22 14:45:35 -06:00
threads.Pair$PairValuesNotEqualException: Pair values not
equal: x: 3, y: 2
at threads.Pair.checkState(CriticalSection.java:37)
2015-12-16 13:50:01 -08:00
at
2016-07-22 14:45:35 -06:00
threads.PairChecker.run(CriticalSection.java:111)
2015-12-16 13:50:01 -08:00
at java.util.concurrent.ThreadPoolExecutor.runWorke
r(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.r
un(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
2015-09-07 11:44:36 -06:00
*/