如果多个线程访问相同的privarte方法,变量值是否会混合?

时间:2015-02-12 13:07:34

标签: java multithreading executorservice

我有一个公共方法,我在其中使用executor框架来创建多个线程,并且所有线程都访问相同的私有方法。

以下代码:

 public String getValue(Map map1, Map map2, Map map3, Map map4) {
    ExecutorService es = Executors.newFixedThreadPool(4);
        CompletionService<Object> cs = new ExecutorCompletionService<Object>(es);

        cs.submit(new Callable<Object>() {
            public Object call() throws Exception {              
               getCount(map1);
                return null;
            }
        });

        cs.submit(new Callable<Object>() {
            public Object call() throws Exception {             
              getCount(map2);
                return null;
            }
        });

        cs.submit(new Callable<Object>() {
            public Object call() throws Exception {             
             getCount(map2);
                return null;
            }
        });

        cs.submit(new Callable<Object>() {
            public Object call() throws Exception {              
               getCount(map3);
                return null;
            }
        });   

        for (int i = 0; i < 4; i++) {
            try {
                cs.take().get(); // find the first completed task
            } catch (InterruptedException e) {
            } catch (ExecutionException e) {
            }
        }

}



 private int getCount(final Map map) { 
        List<String> list = new ArrayList<>();
            for (Map.Entry<> elem : map.entrySet()) {
                      list.add(elem .getValue()) ;           
            }
           int count = 0;
            for(String fields: list){
                 count + =   // Some time consuming DB operation 
              }
           return count;
    }

私有方法或任何Hashmap迭代问题中声明的变量值是否会混淆?

如何调用私有方法?是否有不同线程的私有方法的几个副本或所有线程将同时执行私有方法。

如果你觉得这个问题有点愚蠢,请耐心等待。)

2 个答案:

答案 0 :(得分:1)

如果您询问方法参数和方法内部变量,答案是否定的。这些变量在堆栈上分配,并且每个线程都不同。

编辑: 传递共享(在多个线程中)而不是线程安全对象时可能会发生问题。例如,您的方法foo()接受MyClass类型的参数:

foo(MyClass param) {}

foo()的某个地方,您调用param.bar()(直接或间接)使用非线程安全的成员变量。在这种情况下,你将获得竞争条件。

(感谢@lexicore)

但是对于类字段,线程同步问题是相关的。

答案 1 :(得分:0)

您的代码不应该有任何问题,因为您不会操纵parameters(例如地图中的adding/removing内容。)

当然有这样的假设,那些地图是不相关的(例如sharing same resources AND 否你在程序中的其他地方你将在这个方法的同时操纵这些对象是运行

是的,我的解释可能让读者头疼。但由于使用mapmulti-threaded programming的经验不足,可能会有大量其他问题可能出错。

所以建议尽量让你的程序尽可能thread-safe,即使你非常确定什么都不会出错。