同时搜索多个HashMaps

时间:2015-07-30 11:21:01

标签: java multithreading dictionary hashmap

tldr :如何同时在多个(只读)Java HashMaps中搜索条目?

长版:

我有几个不同大小的词典存储为HashMap< String, String >。一旦他们被读入,他们永远不会被改变(严格只读)。 我想检查是否以及哪个字典用我的密钥存储了一个条目。

我的代码最初正在寻找这样的密钥:

public DictionaryEntry getEntry(String key) {
    for (int i = 0; i < _numDictionaries; i++) {
        HashMap<String, String> map = getDictionary(i);
        if (map.containsKey(key))
             return new DictionaryEntry(map.get(key), i);
    }
    return null;
}

然后它变得有点复杂:我的搜索字符串可能包含拼写错误,或者是存储条目的变体。就像,如果存储的密钥是​​&#34; banana&#34;,我可能会查找&#34; bannana&#34;或者&#34;香蕉&#34;,但仍然想要&#34; banana&#34;回。使用Levenshtein-Distance,我现在遍历所有词典及其中的每个条目:

public DictionaryEntry getEntry(String key) {
    for (int i = 0; i < _numDictionaries; i++) {
        HashMap<String, String> map = getDictionary(i);
        for (Map.Entry entry : map.entrySet) {
            // Calculate Levenshtein distance, store closest match etc.
        }
    }
    // return closest match or null.
}    

到目前为止一切正常,我得到了我想要的条目。不幸的是,我需要查找大约7000个字符串,在五个不同大小的字典中(约30-70k条目),这需要一段时间。从我的处理输出中,我的强烈印象是我的查找主导整个运行时。

我改善运行时的第一个想法是并行搜索所有词典。由于没有一个字典需要更改,并且不会有多个线程同时访问字典,因此我没有看到任何安全问题。

问题是:我该怎么做?我之前从未使用过多线程。我的搜索只提出了Concurrent HashMaps(但根据我的理解,我不需要这个)和Runnable类,我必须将我的处理放入方法run()。我想我可以重写我当前的类以适应Runnable,但我想知道是否有更简单的方法可以做到这一点(或者我怎么能用Runnable做到这一点,现在我的有限理解认为我必须重组很多)。

因为我被要求分享Levenshtein-Logic:它真的没什么特别的,但是你走了:

private int _maxLSDistance = 10;
public Map.Entry getClosestMatch(String key) {
    Map.Entry _closestMatch = null;
    int lsDist;

    if (key == null) {
        return null;
    }

    for (Map.Entry entry : _dictionary.entrySet()) {
        // Perfect match
        if (entry.getKey().equals(key)) {
            return entry;
        }
        // Similar match
        else {
            int dist = StringUtils.getLevenshteinDistance((String) entry.getKey(), key);

            // If "dist" is smaller than threshold and smaller than distance of already stored entry
            if (dist < _maxLSDistance) {
                if (_closestMatch == null || dist < _lsDistance) {
                    _closestMatch = entry;
                    _lsDistance = dist;
                }
            }
        }
    }
    return _closestMatch
}

5 个答案:

答案 0 :(得分:2)

为了在你的情况下使用多线程,可能是这样的:

&#34;监视器&#34; class,它基本上存储结果并协调线程;

sort

Thread it's self,可以设置为搜索特定字典:

public class Results {

    private int nrOfDictionaries = 4; //

    private ArrayList<String> results = new ArrayList<String>();

    public void prepare() {
        nrOfDictionaries = 4;
        results = new ArrayList<String>();
    }

    public synchronized void oneDictionaryFinished() {
        nrOfDictionaries--;
        System.out.println("one dictionary finished");
        notifyAll();
    }

    public synchronized boolean isReady() throws InterruptedException {

        while (nrOfDictionaries != 0) {
            wait();
        }

        return true;
    }

    public synchronized void addResult(String result) {
        results.add(result);
    }

    public ArrayList<String> getAllResults() {
        return results;
    }
}

演示的主要方法:

public class ThreadDictionarySearch extends Thread {

    // the actual dictionary
    private String dictionary;
    private Results results;

    public ThreadDictionarySearch(Results results, String dictionary) {
        this.dictionary = dictionary;
        this.results = results;
    }

    @Override
    public void run() {

        for (int i = 0; i < 4; i++) {
            // search dictionary;
            results.addResult("result of " + dictionary);
            System.out.println("adding result from " + dictionary);
        }

        results.oneDictionaryFinished();
    }

}

答案 1 :(得分:0)

我认为最简单的方法是在条目集上使用流:

public DictionaryEntry getEntry(String key) {
  for (int i = 0; i < _numDictionaries; i++) {
    HashMap<String, String> map = getDictionary(i);

    map.entrySet().parallelStream().foreach( (entry) ->
                                     {
                                       // Calculate Levenshtein distance, store closest match etc.
                                     }
      );
  }
  // return closest match or null.
}

如果你当然使用java 8。您也可以将外部循环包装到IntStream中。您也可以直接使用Stream.reduce获取距离最小的条目。

答案 2 :(得分:0)

也许尝试线程池:

<input type="fecha" class="form-control" id="fecha" ng-model="cf.fecha" value="{{formCtrl.formulario.fecha | date}}"  disabled>

我相信您也可以尝试快速估算完全不匹配的字符串(即长度上的显着差异),并使用它尽快完成逻辑,转移到下一个候选者。

答案 3 :(得分:0)

我非常怀疑HashMaps在这里是一个合适的解决方案,特别是如果你想要一些模糊和停止的话。您应该使用适当的全文搜索解决方案,例如ElaticSearchApache Solr,或者至少使用Apache Lucene之类的可用引擎。

话虽这么说,你可以使用一个穷人的版本:创建你的地图数组和一个SortedMap,迭代数组,获取当前HashMap的键并将它们存储在SortedMap中,并使用其HashMap的索引。要检索密钥,首先在SortedMap中搜索所述密钥,使用索引位置从数组中获取相应的HashMap,并仅在一个HashMap中查找密钥。应该足够快,而不需要多线程来挖掘HashMaps。但是,您可以将下面的代码变为可运行的,并且可以并行进行多次查找。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class Search {

    public static void main(String[] arg) {

        if (arg.length == 0) {
            System.out.println("Must give a search word!");
            System.exit(1);
        }

        String searchString = arg[0].toLowerCase();

        /*
         * Populating our HashMaps.
         */
        HashMap<String, String> english = new HashMap<String, String>();
        english.put("banana", "fruit");
        english.put("tomato", "vegetable");

        HashMap<String, String> german = new HashMap<String, String>();
        german.put("Banane", "Frucht");
        german.put("Tomate", "Gemüse");

        /*
         * Now we create our ArrayList of HashMaps for fast retrieval
         */

        List<HashMap<String, String>> maps = new ArrayList<HashMap<String, String>>();
        maps.add(english);
        maps.add(german);


        /*
         * This is our index
         */
        SortedMap<String, Integer> index = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);


        /*
         * Populating the index:
         */
        for (int i = 0; i < maps.size(); i++) {
            // We iterate through or HashMaps...
            HashMap<String, String> currentMap = maps.get(i);

            for (String key : currentMap.keySet()) {
                /* ...and populate our index with lowercase versions of the keys,
                 * referencing the array from which the key originates.
                 */ 
                index.put(key.toLowerCase(), i);
            }

        }


         // In case our index contains our search string...
        if (index.containsKey(searchString)) {

            /* 
             * ... we find out in which map of the ones stored in maps
             * the word in the index originated from.
             */
            Integer mapIndex = index.get(searchString);

            /*
             * Next, we look up said map.
             */
            HashMap<String, String> origin = maps.get(mapIndex);

            /*
             * Last, we retrieve the value from the origin map
             */

            String result = origin.get(searchString);

            /*
             * The above steps can be shortened to
             *  String result = maps.get(index.get(searchString).intValue()).get(searchString);
             */

            System.out.println(result);
        } else {
            System.out.println("\"" + searchString + "\" is not in the index!");
        }
    }

}

请注意,这是一个相当天真的实现,仅用于说明目的。它没有解决几个问题(例如,您不能有重复的索引条目)。

使用此解决方案,您基本上可以为查询速度交换启动速度。

答案 4 :(得分:0)

好的!! ..

由于您的关注是要加快响应速度。

我建议你在线程之间划分工作。

让你有5个字典可以将三个字典保存到一个线程,其余两个将由另一个线程处理。 然后,女巫线程发现匹配将停止或终止其他线程。

可能你需要一个额外的逻辑去做分工...但这不会影响你的表演时间。

您可能需要对代码进行更改才能获得近距离匹配:

for (Map.Entry entry : _dictionary.entrySet()) {

你正在使用EntrySet但是你并没有使用价值观,因为看起来条目设置有点贵。我建议您只使用keySet,因为您对该地图中的values并不感兴趣

 for (Map.Entry entry : _dictionary.keySet()) {

有关地图性能的详细信息请阅读此链接Map performances

  

迭代LinkedHashMap的集合视图需要与地图大小成比例的时间,无论其容量如何。对HashMap的迭代可能更昂贵,需要与其容量成比例的时间。

相关问题