forked from hansiming/JavaProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerialNumberChecker.java
More file actions
85 lines (59 loc) · 1.54 KB
/
SerialNumberChecker.java
File metadata and controls
85 lines (59 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.csdhsm.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
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
//by the SerialNumberGenerator
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 set = new CircularSet(1000);
private static ExecutorService service = Executors.newCachedThreadPool();
static class SerialChecker implements Runnable{
@Override
public void run() {
while(true){
int serial = SerialNumberGenerator.nextSerialNumber();
if(set.contains(serial)){
System.out.println("Duplicate: " + serial);
System.exit(0);
}
set.add(serial);
}
}
}
public static void main(String[] args) throws Exception {
for(int i = 0; i < SIZE; i++){
service.execute(new SerialChecker());
}
if(args.length > 0){
TimeUnit.SECONDS.sleep(new Integer(args[0]));
System.out.println("No duplicates detected");
System.exit(0);
}
}
}