Возможны ли проблемы с параллелизмом при вызове метода класса из потока? - PullRequest
0 голосов
/ 17 июня 2020
public class ThreadTest {
   private final ListeningExecutorService executor;

public ThreadTest() {
   this.executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
}

public void processAsync() {
 int i=0;
 do {
    final Future<Integer> future = processThread(i));
    futures.add(future);
    i++;
 } while (i<10);
 int count = 0;
    for (Future<Integer> f : futures) {
        try {
            count+=f.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException("Error occurred", e);
        }
    }
}


private Integer updateCount(Integer i) {
    Integer a = Math(i,2);
    a = a + 20;
    Integer b = a + 40;
    return b;
}


public ListenableFuture<Integer> processThread(Integer i) {

    return this.executor.submit(()->{
        return updateCount(i);
    });
}

В этом небольшом фрагменте кода мне нужно было бы синхронизировать что-нибудь в методе updateCount(), если бы я вызвал метод processAsync() класса? Будет ли несколько потоков, вызывающих updateCount(), приводить к тому, что временные переменные created(i, a , b) не синхронизируются и возвращают значения мусора?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...