@Async is not working for me, tried debugging it multiple times but the api was running in same thread.
Am I missing something in my configuration or there is some interplay between the components which I cannot see?
I am debugging by calling the same api 2-3 times with fixed interval of time but all are running in same thread.
Config Class:
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean("threadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AsyncThread-");
executor.initialize();
return executor;
}
}
Method where I want to apply async
@Async("threadPoolTaskExecutor")
public static CompletableFuture<Object> getExecutionDatafromDb() {
long start = System.currentTimeMillis();
Object executionData = "";
db = mongoClient.getDatabase(database);
collection = db.getCollection("executiondata");
Document data = null;
BasicDBObject whereQuery = new BasicDBObject();
Document document = new Document();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
whereQuery.put(MACHINE_ID, 8);
whereQuery.put(PROJECT_ID, 121);
iterDoc = collection.find(whereQuery).cursor();
try {
if (iterDoc.hasNext()) {
data = iterDoc.next();
executionData = data.get("execution_data");
} else {
executionData = createExecutionDataJson();
document.put("execution_data", executionData);
document.put(MACHINE_ID, machineId);
document.put(PROJECT_ID, projectId);
}
} catch (Exception e) {
throw new BusinessException("605",
"Something went wrong in Service layer while fetching Execution Data From Db" + e.getMessage());
}
logger.info("Fecthing data "+Thread.currentThread().getName());
try {
json = ow.writeValueAsString(executionData);
} catch (JsonProcessingException e) {
e.printStackTrace();
} finally {
iterDoc.close();
}
long end = System.currentTimeMillis();
logger.info("Total time {}", (end - start));
return CompletableFuture.completedFuture(json);
}
Api which I want to hit:
@SuppressWarnings("static-access")
@GetMapping(value = "/getExecutionDataByThread", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getExecutionDataByThread() {
Object result1 = asyncService.getExecutionDatafromDb();
sleep(2); // for demonstration
Object result2 = asyncService.getExecutionDatafromDb();
sleep(2);
Object result3 = asyncService.getExecutionDatafromDb();
return ResponseEntity.status(HttpStatus.OK).build();
}
The async method works by wrapping the object with the annotated method in a proxy that gets a thread from the pool and executes the task on it. This works for instance methods of spring managed objects, it doesn't work for static methods. Make the method an instance method.