OnJava8-Examples/threads/SerialNumberChecker.java

70 lines
1.9 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/SerialNumberChecker.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
// Operations that might seem safe are not,
2016-01-25 18:05:55 -08:00
// when threads are present
2015-06-15 17:47:35 -07:00
// {Args: 4}
import java.util.concurrent.*;
// Reuses storage so we don't run out of memory:
class CircularSet {
private int[] array;
private int len;
private int index = 0;
public CircularSet(int size) {
array = new int[size];
len = size;
// Initialize to a value not produced
2015-11-03 12:00:44 -08:00
// by the SerialNumberSupplier:
2015-06-15 17:47:35 -07:00
for(int i = 0; i < size; i++)
array[i] = -1;
}
public synchronized void add(int i) {
array[index] = i;
// Wrap index and write over old elements:
index = ++index % len;
}
public synchronized boolean contains(int val) {
for(int i = 0; i < len; i++)
if(array[i] == val) return true;
return false;
}
}
public class SerialNumberChecker {
private static final int SIZE = 10;
private static CircularSet serials =
new CircularSet(1000);
private static ExecutorService exec =
Executors.newCachedThreadPool();
static class SerialChecker implements Runnable {
@Override
public void run() {
while(true) {
int serial =
2015-11-03 12:00:44 -08:00
SerialNumberSupplier.nextSerialNumber();
2015-06-15 17:47:35 -07:00
if(serials.contains(serial)) {
System.out.println("Duplicate: " + serial);
System.exit(0);
}
serials.add(serial);
}
}
}
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
for(int i = 0; i < SIZE; i++)
exec.execute(new SerialChecker());
// Stop after n seconds if there's an argument:
if(args.length > 0) {
TimeUnit.SECONDS.sleep(new Integer(args[0]));
System.out.println("No duplicates detected");
System.exit(0);
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-22 14:45:35 -06:00
Duplicate: 5178
2015-09-07 11:44:36 -06:00
*/