Я намереваюсь создать 2 потока, чтобы выполнить некоторые вычисления, а затем проверить (каждый из них), завершил ли other также свои вычисления, в противном случае просто завершиться.Когда thread1 узнает, что other (thread2) также завершил свое вычисление, тогда thread1 должен продолжить дополнительное вычисление на основе результата thread2 (в противном случае просто завершится).
Таким образом, я намерен использовать Runnable
ниже с двумя потоками, подобными этому:
me = new CompletableFuture<>();
theOther = new CompletableFuture<>();
executorService.submit(createWorker(data, true, me, theOther));
executorService.submit(createWorker(data++, false, theOther, me));
и Runnable
создается следующим образом:
private Runnable createWorker(int data, boolean callRegion1,
CompletableFuture<Payment> me,
CompletableFuture<Payment> theOther) {
return () -> {
Payment myPayment;
try {
myPayment = postData(data, callRegion1);
me.complete(myPayment);
} catch (Throwable ex) {
me.completeExceptionally(ex);
// comparison with theOther no longer make sense
return;
}
// skip comparison when myPayment is null
if (myPayment == null) {
log.error("myPayment == null for data = {}", data);
return;
}
// get otherPayment and ignore exceptions
Payment otherPayment = theOther.getNow(absentPayment);
// skip comparison when otherPayment is null or not yet available
if (otherPayment == null || otherPayment == absentPayment) {
return;
}
// doing the comparison here
if (otherPayment.getData() + myPayment.getData() != 0) {
log.error("M/M or M/SM for data = {}", data);
System.exit(-1);
}
};
}
Созданный Runnable
явно не синхронизирован, поэтому я боюсь, что код ниже:
theOther.getNow(absentPayment);
может быть оценен в absentPayment
одновременно обоими потоками, что будет плохо для меня (назовем это плохой сценарий ).
В: Возможно ли плохой сценарий и почему?если это невозможно, то почему бы и нет?