'Is mutating two distinct part of an object in an unsynchronized way unsafe?
Lets say I have a relatively simple object with two properties :
@Data
public class MyObject {
public Integer a;
public Integer b;
}
can I safely mutate a in some thread and b in some other thread safely ? for example, would this code be safe from race conditions ?
public MyObject compute() {
MyObject newObj = new MyObject();
List<Runnable> tasks = new ArrayList<>();
Runnable computeATask = () -> {
Integer a = computeA();
newObj.setA(a);
};
Runnable computeBTask = () -> {
Integer b = computeB();
newObj.setB(b);
};
tasks.add(computeATask);
tasks.add(computeBTask);
tasks.stream().parallel().forEach(Runnable::run);
return newObj;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
