I'm currently learning multithreading and I've found something interesting that I can't explain. To the best of my knowledge if two Threads are accessing a static variable they can make their own copies into their cache. An update made by Thread1 to the static variable in its local cache wont reflect in the static variable for Thread2 cache.
For this reason my isFound static variable in Cracker.java should be static and volatile, but it doesnt matter, because all Threads immediately stop when this exit condition is set to true. Can someone explain this to me?
HashDecryptor.java
public class HashDecryptor {
private List<Thread> threads = new ArrayList<>();
// some other fields
public HashDecryptor() {
createThreads();
}
private void createThreads() {
long max = (long) (Math.pow(26, numberOfChars));
int n = numberOfThreads;
for (int i = 0; i < n; ++i) {
if (i == 0) {
threads.add(new Thread(new Cracker(hashToDecrypt, (max * i / n), (max * (i + 1) / n))));
} else {
threads.add(new Thread(new Cracker(hashToDecrypt, (max * i / n) + 1, (max * (i + 1) / n))));
}
}
}
public void startDecryting() {
for (Thread t : threads) {
t.start();
}
}
}
Cracker.java
public class Cracker implements Runnable {
// Some other fields
private static boolean isFound;
public Cracker(String hashToDecrypt, long start, long end) {
this.hashToDecrypt = hashToDecrypt;
this.start = start;
this.end = end;
}
@Override
public void run() {
decrypt();
}
public void decrypt() {
LocalTime startTime = LocalTime.now();
long counter = start;
while (!isFound && counter <= end) {
if (match(counter)) {
isFound = true;
printData(generatePassword(counter), startTime);
}
counter++;
}
}
}