I have a class that I am using to generate 10 character alphanumeric 'tokens' (Strings) and writing them to a txt file.
I would like to be able to generate as many as possible as quickly as possible without producing any duplicates. This is what I have so far:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class TokenGenerator {
public static void main(String[] args) {
for (;;) {
getSaltString();
}
}
public static void getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 10) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
writer(saltStr);
}
public static void writer(String code) {
try {
File file = new File("codes.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
out.println(code);
out.close();
} catch (IOException e) {
System.out.println("Dead");
}
}
}
I was wondering,
A: Is this an efficient way of generating the tokens?
B: How can I call this method using threads to generate them faster
1 Answer 1
Bug 1
Requirement is 'without producing any duplicates'. You have not exactly implemented this (although the chances of happening are really small)
Bug 2
You have no condition of exiting. The program will run forever, and might have inconsistent behaviour if you terminate it externally.
A: Is this an efficient way of generating the tokens?
It can be more efficient.
- You can keep the
File
andWriters
open instead of opening each time. - You can reuse the
new Random()
instead of creating one each time, or.. - ...use
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
- You can use a fixed for loop instead of checking the
salt.length()
.
Also use try-with-resources.
B: How can I call this method using threads to generate them faster
As you write to file, this process will finally be I/O bound, so there is probably no real gain from multi-threading.