簡體   English   中英

奇怪的並發行為

[英]Strange Concurrency Behavior

我目前正在構建的此應用程序中遇到奇怪的行為。

前言

我正在構建的該應用程序的目標很簡單-收集字符串並在多個文本文件中搜索每個字符串。 該應用程序還跟蹤每個字符串的唯一匹配,即,如果字符串“ 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;
    }
}

這應該表現得更好

  • 每個文件只能打開和關閉一次。
  • 線程之間沒有共享數據,因此沒有線程間開銷(最終結果除外)

這將獲取每個文件的匹配項,並在單個線程中累加計數。

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM