Im making a recursive file checking, the problem is i cant have counter inside the method itself, so that i declared it outside. But the problem is, this isnt thread safe.
private int countFiles = 0;
private int getTotalFiles(String path) {
File file = new File(path);
File listFile[] = file.listFiles();
for (File f : listFile) {
if (f.isFile()) {
countFiles++;
}
if (f.isDirectory()) {
getTotalFiles(f.getAbsolutePath());
}
}
return countFiles;
}
Class variable countFiles is not thread safe. How to make this thread safe ?
You don’t need a field, just add the result of the recursive call to
countFiles.