-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTime.java
97 lines (83 loc) · 2.29 KB
/
HashTime.java
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
86
87
88
89
90
91
92
93
94
95
96
97
//Written by Brennan McTernan
//CS511 Assignment 4
import java.io.*;
import java.util.concurrent.*;
import java.util.Random;
//Creates random strings and adds them to a hash table
final class threadTimeStart implements Runnable
{
private String inString;
private static final String ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random rand = new Random();
//Creates a random string
private static String randomString(int len)
{
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(ABC.charAt(rand.nextInt(ABC.length())));
return sb.toString();
}
//Constructor
public threadTimeStart()
{
inString = randomString(10);
}
//Start of each thread
@Override
public void run()
{
try
{
HashTime.execute(inString);
}
catch(InterruptedException ie)
{
System.out.println(Thread.currentThread().getName() + "Has encountered an error");
}
}
}
//Measures time taken to add strings to a hash table
public class HashTime
{
private static ExecutorService service;
private static StringHash stringHash; //initialize hash table, stringHash
public static void main(String[] args)
{
//Check if usage is correct
if(args.length < 4)
{
System.out.println("usage: HashTest num_buckets sleep_time read_write name_of_file");
System.exit(0);
}
//See usage above
long startTime = System.nanoTime();
int numBuckets = Integer.parseInt(args[0]);
int sleepTime = Integer.parseInt(args[1]);
boolean readWrite = Boolean.parseBoolean(args[2]);
int numStrings = Integer.parseInt(args[3]);
//Create hash table, stringHash, and the threadpool with 10 threads
stringHash = new StringHash(numBuckets, sleepTime, readWrite);
service = Executors.newFixedThreadPool(10);
for(int i = 0; i < numStrings; i++)
{
service.submit(new threadTimeStart());
}
service.shutdown();
//Waits for all strings to finish
//Prints out time taken
try
{
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.println("Exiting Hash Time");
System.out.println("Elapsed time: "+ (System.nanoTime() - startTime) + " nano seconds");
}
catch(InterruptedException is)
{
System.out.println("Await termination has fialed.");
}
}
static void execute(String line) throws InterruptedException
{
stringHash.putIfAbsent(line);
}
}