简体   繁体   中英

Alternative to Thread.sleep() for for better performance

I have developed a REST service. The service have one Api endpoint: v1/customer. This Api does two things:

  1. It executes the business logic in main thread
  2. Spawns a child thread to perform the non critical DB writes. The main thread returns response to client immediately, whereas the child thread write to DB asynchronously.

As both of the these operations Step 1 and 2 are not synchronous, it is becoming increasingly challenging to test both of these scenario. Let's say when I try to test the API. I am testing two things (api response and DB writes) As the DB writes happen async fashion. I have to use a Thread.sleep(2000). This process is not scalable and doesn't yield right result. Soon I might have 1000 test cases to run and the total time to run all these testcases will increase enormously. What design technique shall I use to test the DB writes keeping performance and execution time in mind.

I would suggest to change your api design if possible. One possible solution could be to have your first api call respond with http 202 accepted and return some kind of job ID to the client. With this job ID the client could check the progress via a GET on another endpoint. This would allow you to have polling in your test without hardcoding some sleep values.

Here is a example that shows the process in a bit more detail.

https://restfulapi.net/http-status-202-accepted/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM