【问题标题】:Need to use of concurrency in this java method在这个java方法中需要使用并发
【发布时间】:2014-08-27 20:41:03
【问题描述】:

所以我有以下代码,它接受两个数组的输入,并应用一些查询来匹配来自Array1 的元素与来自Array2 的元素,然后它返回两个数组列表中相似的元素数量。

这是我使用的代码:

    public static void get_ND_Matches() throws IOException{
    @SuppressWarnings("rawtypes")
    List<String> array1 = new ArrayList<String>();
    List<String> array2 = new ArrayList<String>();
    array1 = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());
    array2 = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
    String maxLabel="";
    HashMap<String,Integer> map = new HashMap<String,Integer>();
    int number;     
    HashMap<String,ArrayList<String>> theMap = new HashMap<>();
    
    for(String yagoClass:array2){
        theMap.put(yagoClass, getListTwo(yagoClass));
        System.out.println("Done for : "+yagoClass );
    }       
    for(String dbClass:array1){
        ArrayList<String> result = get_2D_Matches(dbClass);
        for(Map.Entry<String, ArrayList<String>> entry : theMap.entrySet()){
            String yagoClass=entry.getKey();
            Set<String> IntersectionSet =Sets.intersection(Sets.newHashSet(result), Sets.newHashSet(entry.getValue()));
            System.out.println(dbClass + " and "+ yagoClass+ " = "+ IntersectionSet.size());
            number = IntersectionSet.size();
            map.put(yagoClass, number);
        }   
        int maxValue=(Collections.max(map.values()));
        for(Entry<String, Integer> entry:map.entrySet()){
            if(entry.getValue()==maxValue && maxValue != 0){
                 maxLabel = entry.getKey();
            }
            if(maxValue==0){
                maxLabel = "Nothing in yago";
            }
        }
        System.out.println("-------------------------------");
        System.out.println(dbClass+" from DBPEDIA Corresponds to "+ maxLabel);
        System.out.println("-------------------------------");
        
    }
}

此代码返回例如:

来自 DBPEDIA 的演员对应于 Yago_Actor

来自 DBPEDIA 的专辑对应于 Yago_Album

来自 DBPEDIA 的 SomeClass 对应于 Yago 中的任何内容

等等。

在幕后,此代码使用getDBpediaClasses,然后应用Get_2D_Matches(); 方法来获取每个类的结果数组列表。然后将结果的每个 ArrayList 与 getListTwo() 为每个 fileToArrayListYago() 的类生成的另一个 ArrayList 进行比较。

现在,由于所有计算都是在后台进行的(每个数组中有数百万个元素),这个过程需要几个小时才能执行。

我真的很想使用并发/多线程来解决这个问题。谁能告诉我怎么做?

【问题讨论】:

标签: java multithreading optimization concurrency


【解决方案1】:

并行化不完全干净和优化的代码几乎没有意义。您可能会在典型的 4 核 CPU 上获得因子 4 或根本没有,这取决于您是否选择要正确并行化的部分。使用更好的算法可能会给你更多。

瓶颈可能是get_2D_Matches,您还没有发布。

直接计算最大值而不是创建一个一次性的HashMap&lt;String,Integer&gt; map 可以节省相当多的时间,因此可以将Sets.newHashSet(result) 移出循环。

你真的应该重新考虑变量命名。对于像 maptheMapresult 这样的名称(对于不是方法结果的东西),很难找出发生了什么。

如果你真的想并行化它,你需要先拆分你的超长方法。然后就相当简单了,因为每个dbClass 的处理都可以独立完成。只需将其封装为Callable 并提交给ExecutorService

不过,我建议先清理代码,然后将其提交给CR,然后再考虑并行化。

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多