我正在构建这个应用程序中的奇怪行为。
我正在构建的这个应用程序有一个简单的目标 - 获取字符串集合并在多个文本文件中搜索每个字符串。该应用程序还会跟踪每个字符串的唯一匹配,即如果字符串“abcd”在文件A中出现n次,则只计算一次。
由于此应用程序主要处理大量文件和大量字符串,因此我决定在后台创建一个实现Runnable并使用ExecutorService运行Runnable任务的类。我还决定调查字符串搜索的快速性,因此我开始使用不同的字符串匹配方法(即String.contains()
,String.indexOf()
,Boyer-Moore算法)比较时间。我从http://algs4.cs.princeton.edu/53substring/BoyerMoore.java.html抓取了Boyer-Moore算法的源代码,并将其包含在我的项目中。这是问题的起源......
我注意到在使用BoyerMoore
类时,字符串搜索会返回不同的结果(每次我运行搜索,找到的字符串的数量会有所不同)所以我将其替换为String.contains()
,以便代码如下所示......
private boolean findStringInFile(String pattern, File file) {
boolean result = false;
BoyerMoore bm = new BoyerMoore(pattern); // This line still causes varying results.
try {
Scanner in = new Scanner(new FileReader(file));
while(in.hasNextLine() && !result) {
String line = in.nextLine();
result = line.contains(pattern);
}
in.close();
} catch (FileNotFoundException e) {
System.out.println("ERROR: " + e.getMessage());
System.exit(0);
}
return result;
}
即使使用上述代码,结果仍然不一致。似乎BoyerMoore
对象的实例化导致结果变化。我挖得更深一些,发现BoyerMoore
构造函数中的以下代码导致了这种不一致...
// position of rightmost occurrence of c in the pattern
right = new int[R];
for (int c = 0; c < R; c++)
right[c] = -1;
for (int j = 0; j < pat.length(); j++)
right[pat.charAt(j)] = j;
现在我知道导致不一致的但我仍然不明白为什么它正在发生。在多线程方面,我不是老手,因此非常感谢任何可能的解释/见解!
private class Search implements Runnable {
private File mSearchableFile;
private ConcurrentHashMap<String,Integer> mTable;
public Search(File file,ConcurrentHashMap<String,Integer> table) {
mSearchableFile = file;
mTable = table;
}
@Override
public void run() {
Iterator<String> nodeItr = mTable.keySet().iterator();
while(nodeItr.hasNext()) {
String currentString = nodeItr.next();
if(findStringInFile(currentString , mSearchableFile)) {
Integer count = mTable.get(currentString) + 1;
mTable.put(currentString,count);
}
}
}
private boolean findStringInFile(String pattern, File file) {
boolean result = false;
// BoyerMoore bm = new BoyerMoore(pattern);
try {
Scanner in = new Scanner(new FileReader(file));
while(in.hasNextLine() && !result) {
String line = in.nextLine();
result = line.contains(pattern);
}
in.close();
} catch (FileNotFoundException e) {
System.out.println("ERROR: " + e.getMessage());
System.exit(0);
}
return result;
}
}
答案 0 :(得分:2)
这应该表现得更好
这将获取每个文件的匹配项,并在单个线程中累计计数。
static class Search implements Callable<Set<String>> {
private final File file;
private final Set<String> toFind;
private final long lastModified;
public Search(File file, Set<String> toSearchFor) {
this.file = file;
lastModified = file.lastModified();
toFind = new CopyOnWriteArraySet<>(toSearchFor);
}
@Override
public Set<String> call() throws Exception {
Set<String> found = new HashSet<>();
Scanner in = new Scanner(new FileReader(file));
while (in.hasNextLine() && !toFind.isEmpty()) {
String line = in.nextLine();
for (String s : toFind) {
if (line.contains(s)) {
toFind.remove(s);
found.add(s);
}
}
}
in.close();
if (file.lastModified() != lastModified)
throw new AssertionError(file + " was modified");
return found;
}
}
public static Map<String, AtomicInteger> performSearches(
ExecutorService service, File[] files, Set<String> toFind)
throws ExecutionException, InterruptedException {
List<Future<Set<String>>> futures = new ArrayList<>();
for (File file : files) {
futures.add(service.submit(new Search(file, toFind)));
}
Map<String, AtomicInteger> counts = new LinkedHashMap<>();
for (String s : toFind)
counts.put(s, new AtomicInteger());
for (Future<Set<String>> future : futures) {
for (String s : future.get())
counts.get(s).incrementAndGet();
}
return counts;
}
这些行不是线程安全的。任意数量的线程都可以更新相同的密钥,因此结果将不安全。
Integer count = mTable.get(currentString) + 1;
// another thread could be running here.
mTable.put(currentString,count);
一个简单的解决方法是使用AtomicInteger(它也会简化您的代码)
private final ConcurrentHashMap<String, AtomicInteger> mTable;
for(Map.Entry<String, AtomicInteger> entry: mTable.entrySet())
if(findStringInFile(entry.getKey(), mSearchableFile))
entry.getValue().incrementAndGet();