March 31, 2024

Sleep Method in Java Multi-Threading

Thread.sleep() method in Java multi-threading causes the currently executing thread to suspend execution for a specified period.

In Java Thread class there are two overloaded sleep() methods-

  1. static void sleep(long millis) throws InterruptedException- Causes the currently executing thread to sleep for the specified number of milliseconds.
  2. static void sleep(long millis, int nanos) throws InterruptedException- Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

Important points about sleep() method in Java

  1. If the value of milliseconds is negative then IllegalArgumentException is thrown.
  2. If the value of nanoseconds is not in the range 0-999999 then IllegalArgumentException is thrown.
  3. Though you provide the duration thread is supposed to sleep as an argument in sleep method but that depends on the precision and accuracy of system timers and how schedulers are implemented in underlying OS.
  4. If thread is holding any lock, ownership of that lock is not released when thread is paused using sleep() method.
  5. A sleeping thread can also be interrupted thus terminating the sleep period.

Advantage of using sleep() method

sleep() method in Java helps in making processor time available to the other threads of an application or other applications that might be running on a computer system.

While developing your multi-threading application, using sleep() method, you can simulate some delay that may occur in production environment when your application is accessed by many users and executing many threads. That will help you to find out some of the errors that may crop up later.

Example using sleep() method

public class InterruptDemo implements Runnable {
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        System.out.println("Thread " + Thread.currentThread().getName() + " interrupted, reason " + e.getMessage());        
        throw new RuntimeException("Thread interrupted", e);
      }
    }	
  }

  public static void main(String[] args) {
    Thread t = new Thread(new InterruptDemo());
    long startTime = System.currentTimeMillis();
    t.start();
    try {
      t.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
      System.out.println("Total thread pause time - " + (System.currentTimeMillis() - startTime));
  }
}
Output
Total thread pause time – 2527

As you can see loop in the run() method runs for 5 times so total sleep time would be 2500 ms but it is not that duration precisely.

That's all for the topic Sleep Method in Java Multi-Threading. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment