简体   繁体   中英

Can I use Thread.sleep in a servlet to add random delays for the local server to answer my api call?

My deployed server has sometimes long response times, while working and developing at localhost all calls are really fast.

This has made my application enter unexpected behaviour once deployed a few times due to problems with resource loading taking too long.

I'd like to simulate in my local tests the bad connection with my real server, therefore I want to add a random delay to every request-response and my first thought was to use Thread.sleep in the servlet:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    //add delay before processing request
    if (DELAY > 0){
        int delay;
        if (RANDOMIZE){
            delay = Random.nextInt(DELAY);
        } else {
            delay = DELAY;
        }
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e1) {
            logger.error(e1);
        }
    }
...

However I have read that one should not use Thread.sleep() inside a servlet, but the context of such discouragement and their solutions are drastically different from my case, can I use thread.sleep() in this context?

EDIT: This is of course only for local and for the client to be strained a bit in the local tests... I just want to simulate the bad network I've encountered in reality!

I think this whole approach is flawed. I wouldn't introduce a random delay (how are you going to repeat test cases?). You can introduce a Thread.sleep() , but I wouldn't. Would this be in your production code ? Is it configurable ? What happens if it's accidentlally turned on in production ?

I would rather set up a test server with the exact characteristics of your production environment. That way you can not only debug effectively, but build a regression test suite that will allow you to develop effectively, knowing how the application will perform in production.

Perhaps the one concession to the above is to introduce network delays (as appropriate) between client and server if your users are geographically diverse. That's often done using a hardware device on the network and wouldn't affect your code or configuration.

I did this to get delay :

response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
    out.println("<meta http-equiv=\"Refresh\" content=\"3;url=home.jsp/\">");
}

Remember that in content=\\"3;url=home.jsp/\\" , 3 is the delay seconds and home.jsp is the page you want to go to after the given seconds.

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