0

I have network requirement who forces me to idle request sending for 2 seconds

requester = new Thread(){
        @Override
        public void run(){
                  buildRequest();
                  Thread.sleep(requestDelay);
                } catch( InterruptedException e){
                   // keep idle for the remaining time still
                   // interrupted at 1s need to sleep 1 second more
                   e.printStackTrace();
                }
                sendRequest();
            }
        }

Is it possible to still sleep for remaining time with consuming CPU with a loop? If yes is the best way ?

Hassam Abdelillah
  • 2,246
  • 3
  • 16
  • 37
  • 3
    Of course it's possible, but it would be best not to sleep at all. Use a reactive pattern to fire an even after a few minutes to wake the request - that way you don't "waste" threads. – Boris the Spider Dec 10 '18 at 18:39
  • 4
    Interrupts don’t happen by accident. If your thread is interrupted, someone is explicitly asking it to stop what it’s doing and exit gracefully. Are you sure you want to ignore that? – VGR Dec 10 '18 at 18:44
  • Guava has [`Uninterruptibles.sleepUninterruptibly`](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/util/concurrent/Uninterruptibles.html#sleepUninterruptibly(long,%20java.util.concurrent.TimeUnit)). Basically, it just records the fact the thread was interrupted, clears the flag, and goes back to sleep. Once the full time has expired, it re-interrupts if it was interrupted. – Andy Turner Dec 10 '18 at 18:55
  • I know that sleep would be a bad idea from the start. But given this option, would be another sleep appropriate in the catch scope from the remaining time ? – Hassam Abdelillah Dec 10 '18 at 20:58

1 Answers1

2

If I understood correctly you want to handle the InterruptedException in such way to unsure a delay before executing sendRequest. Well, since the InterruptedException happens when something calls interrupt() on the thread, that catch block doesn't get executed so you don't have to worry about.

Your approach is not quite right, a reactive approach would be better. Even a basic Timer is better.