java - 线程如何在 Spring Async 函数中成功终止以及如何在 java 中的多线程方法中递归调用相同的函数
问题描述
我正在@Async
从我的控制器调用函数,看起来线程在完成类中的makeCallWithRestTemplate
方法后没有终止HttpServiceClient
。
- 问题 1-如何确保线程在执行任务后关闭?
- 我有两种类型的任务 - 独立任务和依赖任务。现在我的要求是我将获得任务列表作为输入,我需要先执行所有独立任务,然后根据如下条件执行相关任务
问题2-一旦所有独立任务都将执行,请在此处等待,现在我的问题是如何在此处等待?
问题3-一旦等待完成再次调用具有依赖任务的restTemplate.exchange方法,我怎样才能使其递归,我的hashmap在递归中会是线程安全的吗?
- 问题 4-在
makeCallWithRestTemplate
方法中,我正在使用 hashmap,它进一步传递给提取的私有方法,现在我的下一个问题是,hashmap 在多线程环境中是否安全,因为对我来说它是一个局部变量,对于不同的线程会有所不同?或者我需要在这里使用 ConcurrentHashmap 吗?如何测试它?
请求结构
[
{ independent task 1
},
{ dependent task 1,
"dependency": { // dependency is that, execute task 1 first
and then based on its result code execute dependent task 1
"===": [
"$[0].response.http_body.action.result_code",
"SUCCESS"
]
}
}
]
控制器
@RestController
@RequestMapping("/abc")
public class ActionController {
@Autowired
private HttpServiceClient client;
@PostMapping
public ResponseEntity<JsonNode> performMultipleActions(@RequestBody List<List<ABC>> abc) {
return client.callExternalService(abc);
}
}
@Component
public class HttpServiceClient {
@Autowired
private RestTemplate restTemplate;
@Async
public CompletableFuture<Map<Integer, ResponseEntity<JsonNode>>> makeCallWithRestTemplate(
List<ABC> requests) throws IOException {
int index = -1;
Map map = new hashmap();
while (iterator.hasNext()) {
index++;
Abc abc = iterator.next();
if (dependency == null) {
extracted(mapOfResult, index, action);
}else{
//create a map of with index as a key and object as a value
map.put(index, request);
}
// **Question 3-** once all the independent task will get executed wait here, Now my question is how to wait here ?
//**Question 4-** once wait complete again call restTemplate.exchange method with dependent task, how can i make it recursive, will my hashmap would be threadsafe in recursive?
}
return CompletableFuture.completedFuture(exchange);
}
}
private void extracted(Map<Integer, ResponseEntity<JsonNode>> mapOfResult, int index, ActionRequest action)
throws JsonProcessingException, JsonMappingException {
ResponseEntity<JsonNode> exchange = restTemplate.exchange(urlObj,
HttpMethod.resolve(action.getMethod()), entity, JsonNode.class);
mapOfResult.put(index, exchange);
}
解决方案
推荐阅读
- python - 如何从极坐标/笛卡尔点创建图像?
- angular - 如何在角度模板文件中显示base64 pdf
- php - imagecreatefrompng() 生成黑色背景而不是图像中的透明部分
- rollup - 如何将其他捆绑包添加到 Sapper 汇总项目
- java - 单击 ImageButton 后,我想创建一个声音并移动下一个活动
- angular - 如何解决 Uncaught TypeError: Object(...) is not a function?
- typescript - 如何解释 IDB 中 KnownKeys 类型的含义?
- mysql - 在 json 列中保存数字或字符串而无需指定键?这可能吗?
- javascript - 如何在 vue.js 中调用 webassembly 方法?
- python - 填充已经拆分的 numpy 数组