2016-12-07 10:34:41 -08:00
|
|
|
// lowlevel/SerialNumberChecker.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 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.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2017-01-15 16:00:44 -08:00
|
|
|
// Test SerialNumbers implementations for thread-safety
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.concurrent.*;
|
2016-12-21 11:06:49 -08:00
|
|
|
import onjava.Nap;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2017-01-12 16:49:36 -08:00
|
|
|
public class SerialNumberChecker implements Runnable {
|
|
|
|
private CircularSet serials = new CircularSet(1000);
|
2017-01-15 16:00:44 -08:00
|
|
|
private SerialNumbers producer;
|
|
|
|
public SerialNumberChecker(SerialNumbers producer) {
|
|
|
|
this.producer = producer;
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public void run() {
|
2017-01-12 16:49:36 -08:00
|
|
|
while(true) {
|
2017-01-15 16:00:44 -08:00
|
|
|
int serial = producer.nextSerialNumber();
|
2017-01-12 16:49:36 -08:00
|
|
|
if(serials.contains(serial)) {
|
|
|
|
System.out.println("Duplicate: " + serial);
|
|
|
|
System.exit(0);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2017-01-12 16:49:36 -08:00
|
|
|
serials.add(serial);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
2017-01-15 16:00:44 -08:00
|
|
|
static void test(SerialNumbers producer) {
|
2017-01-12 16:49:36 -08:00
|
|
|
for(int i = 0; i < 10; i++)
|
|
|
|
CompletableFuture.runAsync(
|
2017-01-15 16:00:44 -08:00
|
|
|
new SerialNumberChecker(producer));
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(4, "No duplicates detected");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|