Here is my code:
class A{
@Autowired
B objB;
public method1(){
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
List<CompletableFuture<String>> listOfFuture ids.stream()
.map(id -> CompletableFuture.supplyAsync(() ->
objB.method2(id)).collect(toList());
}
}
class B{
@Inject
D objD;
@Inject
E objE
public String method2(String id){
String transformedId = objD.method3(id);
return objE.method4(transformedId);
}
}
class B has method2 has objects which are not thread safe. I want to make new instances of B so that each thread has its own objects while executing method2. I can use spring's async utility for method2 and call this method asynchronously from A instead of using CompletableFuture in class A. This will make method2 thread safe. How can I make method2 thread safe if I used CompletableFuture? Is my assumption correct that I need different object for Class B every time I spawn a thread to invoke method2 since class B is not thread safe?