Reputation: 169
So when I visit an enpoint(POST request), I first check if an entry already exists in my database. If yes, I want to return it to the user (for tracking purposes) and continue an operation. But I would like to return the id to the user and continue this process. How to achieve this??
@RestController
public class StudentController {
@Autowired
private StudentService service;
@PostMapping("/storeInDB")
@ResponseBody
public File_Tracking saveStudentDetails(@RequestBody Student student ) throws IOException {
List<Students> student = new ArrayList<>();
int continue = 0;
int id = 0;
id = service.getId(); // I want to return this and continue some other process which follows
Upvotes: 4
Views: 15619
Reputation: 377
In addition to Sandeep Lakdawala's answer, since these two operations should follow each other (the id should be returned to the user first, then the operation should contunie) you should consider scheduling your different threads. Normally, the computers give clock time to threads randomly.
For instance, if we have thread t1 and thread t2, and these t1 prints "hey" to the console and t2 prints "wow!" to the console, when you start your program you can see one of the following in your console:
hey hey hey wow! wow!
or
wow! hey hey wow! wow!
Therefore, in order to achieve your goal, you should search about thread synchronization. Also, you can visit the site "https://www.baeldung.com/java-thread-safety" in order to learn about the synchronization of the threads in Java.
Also, before completing this task, I would suggest you to read about threads and processes because they are very critical topics of computer science. "What is the difference between a process and a thread?" would be a good starting point.
Upvotes: 2
Reputation: 492
You can run the process asychronously in a different thread ,while your main thread returns the id as the service response.
Check this blog about how to define Async operations using spring @Async annotation https://www.baeldung.com/spring-async
Upvotes: 7