How to make recursive call (getTotalFiles) thread safe?

Im doing a recursive check on files, the problem is that I cannot have a counter inside the method itself, so I declared it outside. But the problem is that it is not 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;
}

      

The variable countFiles class is not thread safe. How do I make this stream safe?

+3


source to share


2 answers


You don't need the field, just add the result of the recursive call to countFiles

.



private int getTotalFiles(String path) {
    //...
    if (f.isFile()) {
        countFiles++;
    }
    if (f.isDirectory()) {
        countFiles += getTotalFiles(path);
    }
}

      

+8


source


I don't see a clear reason why countFiles should be a class level variable. You can make your code thread safe by making countFiles a local variable that is returned by the method anyway.



+3


source







All Articles