2015-11-03 12:00:44 -08:00
|
|
|
// concurrency/MutexEvenSupplier.java
|
2015-06-15 17:47:35 -07:00
|
|
|
// Preventing thread collisions with mutexes.
|
|
|
|
// {TimeOutDuringTesting}
|
|
|
|
import java.util.concurrent.locks.*;
|
|
|
|
|
2015-11-03 12:00:44 -08:00
|
|
|
public class MutexEvenSupplier extends IntSupplier {
|
2015-06-15 17:47:35 -07:00
|
|
|
private int currentEvenValue = 0;
|
|
|
|
private Lock lock = new ReentrantLock();
|
|
|
|
@Override
|
|
|
|
public int next() {
|
|
|
|
lock.lock();
|
|
|
|
try {
|
|
|
|
++currentEvenValue;
|
|
|
|
Thread.yield(); // Cause failure faster
|
|
|
|
++currentEvenValue;
|
|
|
|
return currentEvenValue;
|
|
|
|
} finally {
|
|
|
|
lock.unlock();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2015-11-03 12:00:44 -08:00
|
|
|
EvenChecker.test(new MutexEvenSupplier());
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output: (None) */
|