I was asked this question on a exam to count words using multithreading. There are many ways of doing the above task. Producer/consumer with sync, others without sync. What I stumbled upon is using static variables to keep total count of words across all threads. I want to count total words across all files. I wrote this code and expected to not work because static variables are not thread safe. My question if static variables are not thread safe then why is the below code working.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordCount implements Runnable {
String fileName;
static int totalCount = 0;
static int numThreads = 0;
public WordCount(String[] files) {
for (String file : files) {
new Thread(this, file).start();
}
}
public void run() {
int count = 0;
try {
Scanner in = new Scanner(new File(Thread.currentThread().getName()));
while (in.hasNext()) {
in.next();
count++;
}
System.out.println(Thread.currentThread().getName() + ": " + count);
totalCount += count;
numThreads++;
totalCount();
} catch (FileNotFoundException e) {
System.out.println(Thread.currentThread().getName() + ": Not Found");
}
}
public void totalCount() {
if (numThreads == 3) {
System.out.println("total: " + totalCount);
}
}
public int getTotalWords() {
return totalCount;
}
}