誰かがこのコードをレビューして、スレッドセーフかどうかを確認できますか?
public class FileLinesSorter {
private CountDownLatch startSignal = new CountDownLatch(1);
/**
* The lines
*/
private List<String> lines;
/**
* Read files from the file paths
* @param filePaths the list of file paths
* @throws IOException on I/O error
*/
public void readFiles(String[] filePaths) throws IOException {
lines = new ArrayList<String>();
for (String filePath : filePaths) {
File file = new File(filePath);
if (!file.exists()) {
// File does not exist. Log it.
continue;
}
List<String> fileLines = readFile(file);
lines.addAll(fileLines);
}
if (!lines.isEmpty()) {
Collections.sort(lines);
}
startSignal.countDown();
}
/**
* Read a single file
* @param file the file
* @return the file content
* @throws IOException on I/O error
*/
private List<String> readFile(File file) throws IOException {
List<String> contents = new ArrayList<String>();
BufferedReader reader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file.getAbsolutePath());
reader = new BufferedReader(fileReader);
String line = "";
while ((line = reader.readLine()) != null) {
if (line.isEmpty()) {
continue;
}
contents.add(line);
}
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
if (fileReader != null) {
fileReader.close();
}
if (reader != null) {
reader.close();
}
}
return contents;
}
public Iterator<String> getIterator() {
try {
startSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return lines.iterator();
}
public static void main(String[] args) throws Exception {
String[] filePaths = {"C:\\Works\\files\\example-1 copy.txt", "C:\\Works\\files\\example-2 copy.txt"};
FileLinesSorter sorter = new FileLinesSorter();
sorter.readFiles(filePaths);
Iterator<String> lines = sorter.getIterator();
while (lines.hasNext()) {
System.out.println(lines.next());
}
}
}