I have a thread that invokes two separate threads. It passes in the same CompletableFuture
to both of those child threads. If .get()
was called in both of those threads at the exact same time, would I get any type of concurrency issues?
- could it corrupt the
CompletableFuture
? - is it possible that I don’t see the last changes done on the object returned by
.get()
? - what if I modify that object afterwards?
As a concrete example, in the following code, would it be possible that the two threads print a different value, assuming nothing changes the object returned by cfInput.get()
after cfInput
is completed?
public void mainClass(CompletableFuture<ObjA> cfInput){
class1.doAsync1(cfInput);
class2.doAsync2(cfInput);
}
@Async
public void doAsync1(CompletableFuture<ObjA> cfInput){
//logic
System.out.println(cfInput.get().getObjB().getBlah());
//logic
}
@Async
public void doAsync2(CompletableFuture<ObjA> cfInput){
//logic
System.out.println(cfInput.get().getObjB().getBlah());
//logic
}
public class ObjA{
private ObjB objB;
public ObjB getObjB();
public void setObjB();
}
public class ObjB{
private String blah;
public String getBlah();
public void setBlah();
}
get()
could not be safely called from more than one thread. It's entirely reasonable to think that more than one thread in some multi-threaded program might need to await the result of a computation or a query, and if you're usingCompletableFuture
, then you are, by definition, doing multi-threaded programming.get()
? But that is your object, right? I mean, it's whatever object your code supplied to complete the future. Your code example doesn't show where that object comes from or even, the type of that object. So unless you show more code, you are the only person who can say whether it's thread-safe or not.CompletableFuture
anymore. You're asking about the object returned byget
, which is a custom object and will follow whatever thread safety rules you choose to implement in it. Onceget
returns, you're no longer inCompletableFuture
territory.