OnJava8-Examples/lowlevel/SerialNumberChecker.java

59 lines
1.5 KiB
Java
Raw Normal View History

2016-12-07 10:34:41 -08:00
// lowlevel/SerialNumberChecker.java
2016-12-30 17:23:13 -08:00
// (c)2017 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.
2015-06-15 17:47:35 -07:00
// Operations that might seem safe are not,
2017-01-12 16:49:36 -08:00
// when threads are present.
import java.util.*;
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
// Reuses storage so we don't run out of memory:
class CircularSet {
private int[] array;
2017-01-12 16:49:36 -08:00
private int size;
2015-06-15 17:47:35 -07:00
private int index = 0;
public CircularSet(int size) {
array = new int[size];
// Initialize to a value not produced
2015-11-03 12:00:44 -08:00
// by the SerialNumberSupplier:
2017-01-12 16:49:36 -08:00
Arrays.fill(array, -1);
this.size = size;
2015-06-15 17:47:35 -07:00
}
public synchronized void add(int i) {
array[index] = i;
// Wrap index and write over old elements:
2017-01-12 16:49:36 -08:00
index = ++index % size;
2015-06-15 17:47:35 -07:00
}
public synchronized boolean contains(int val) {
2017-01-12 16:49:36 -08:00
for(int i = 0; i < size; i++)
2015-06-15 17:47:35 -07:00
if(array[i] == val) return true;
return false;
}
}
2017-01-12 16:49:36 -08:00
public class SerialNumberChecker implements Runnable {
private CircularSet serials = new CircularSet(1000);
@Override
public void run() {
while(true) {
int serial =
SerialNumberSupplier.nextSerialNumber();
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
}
}
2016-12-21 11:06:49 -08:00
public static void main(String[] args) {
2017-01-12 16:49:36 -08:00
for(int i = 0; i < 10; i++)
CompletableFuture.runAsync(
new SerialNumberChecker());
new Nap(4000, "No duplicates detected");
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-27 11:12:11 -06:00
Duplicate: 4119
2015-09-07 11:44:36 -06:00
*/