简体   繁体   中英

If Multiple threads access same privarte method, will the variables value get mixed?

I have a public method inside which I am using executor framework to create multiple threads and all threads are accessing the same private method.

Code below:

 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;
    }

Will there be any mixing up of value of variable declared in private method or any Hashmap iteration problem?

How the private method gets invoked? Will there be several copies of private method for different thread or all threads will execute the private method simultaneously.

Please bear with me if you find the question a little dumb :)

If you are asking about method argument and method internal variables the answer is no. These variables are allocated on stack and are different for each thread.

EDIT: Issues may happen when passing shared (among several threads) not thread safe objects. For example your method foo() accepts parameter of type MyClass :

foo(MyClass param) {}

Somewhere into foo() you call param.bar() that operates (directly or indirectly) with not thread safe member variable. In this case you will get race condition.

(thanks to @lexicore)

The threads synchronization issues are relevant however for class fields.

There shouldn't be any problems with your code since you don't manipulate the parameters (eg adding/removing stuff from the maps ).

of course there is this assumption that those maps are not related (eg sharing same resources ) AND no where else in you program you will manipulate those objects at the same time of this method is running.

Yes my explanation may give the readers some headache. but out of experience working with map and multi-threaded programming , there could be tons of other stuff that could go wrong.

So a word of advice try to make your program as thread-safe as possible, even though you are very sure that nothing would go wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM