Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips

What is TimeUnit inwards Java
TimeUnit
inwards Java is a aeroplane on java.util.concurrent package, introduced inwards Java five along amongst CountDownLatch, CyclicBarrier, Semaphore in addition to several other concurrent utilities. TimeUnit provides a human readable version of Thread.sleep() method which tin last used inwards house of former. From long fourth dimension Thread's sleep() method is measure agency to interruption a Thread inwards Java in addition to almost every Java programmer is familiar amongst that. In fact, slumber method itself is a rattling pop in addition to has appeared on many Java interviews. The divergence betwixt hold off in addition to sleep is 1 of the tough Java questions to answer. If you lot conduct maintain used Thread.sleep() earlier in addition to I am certain you lot do, you lot powerfulness last familiar amongst a fact similar it's a static method, it doesn't liberate the lock when pausing Thread in addition to it throws InterruptedException

But what many of us doesn't take in a potential final result is readability. Thread.sleep() is an overloaded method in addition to bring long millisecond in addition to long nanosecond, which makes it difficult for programmers to detect out just how many seconds, minutes, hours or twenty-four hours electrical current Thread is sleeping. Look at below instance of Thread's sleep() method:

Thread.sleep(2400000);


By merely having a cursory glance, tin you lot figure out how long electrical current Thread volition wait ? Some of you lot may last but its hardly readable for many Java programmer in addition to you lot ask to convert milliseconds farther into seconds in addition to hence into minutes. Let's bring a hold off on some other instance of Thread.sleep() method which is slightly to a greater extent than readable than previous example.

Thread.sleep(4*60*1000);

This is much meliorate than previous 1 but nevertheless its non perfect in addition to until you lot are aware that slumber times are inwards millisecond its non slow to estimate that electrical current Thread volition hold off for 4 minutes. TimeUnit aeroplane resolves this final result past times providing indicator for DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS in addition to NANOSECONDS. java.util.concurrent.TimeUnit is perfect instance of powerful Java Enum. All TimeUnit are Enum instances. Let's come across how to slumber Thread for 4 minutes using TimeUnit :

TimeUnit.MINUTES.sleep(4);  // sleeping for 4 minutes

Similarly you lot tin innovate pauses on seconds, minutes in addition to hour level. By looking this code you lot tin detect out that, this is much to a greater extent than readable than Thread's slumber method. Remember that TimeUnit.sleep() internally calls Thread.sleep() for sleeping in addition to throws InterruptedException. You tin likewise banking concern gibe JDK code to verify that. Here is a sample code instance which demonstrate how to job TimeUnit's sleep() method inwards Java.

/**
 *
 * Java computer program to demonstrate how to job TimeUnit.sleep() method inwards Java.
 * TimeUnit is a novel agency of introducing interruption inwards Java program.
 * @author Javin
 */

public class TimeUnitTest {

    public static void main(String args[]) throws InterruptedException {

        System.out.println("Sleeping for 4 minutes using Thread.sleep()");
        Thread.sleep(4 * 60 * 1000);
        System.out.println("Sleeping for 4 minutes using TimeUnit sleep()");
     
        TimeUnit.SECONDS.sleep(4);
        TimeUnit.MINUTES.sleep(4);
        TimeUnit.HOURS.sleep(1);
        TimeUnit.DAYS.sleep(1);
    }
}


Apart from sleep() functionality, TimeUnit likewise furnish convenient method to convert fourth dimension into unlike Unit. For instance if you lot desire to convert seconds into milliseconds than you lot tin job next code :

TimeUnit.SECONDS.toMillis(44)

It volition render 44,000. It's readable in addition to convenient agency to convert fourth dimension into unlike unites e.g. micro seconds, Milli seconds etc.



TimeUnit vs Thread.sleep()

Java programmer knows nigh it in addition to past times looking Thread.sleep() they come upward to know that Thread is going to pause. This is non truthful amongst TimeUnit class, amongst 2 argue source its non rattling pop at to the lowest degree compare to Thread.sleep() in addition to 2nd it's non inwards Thread class, much similar wait in addition to notify which are likewise non inwards Thread class.. Anyway none of these are big issues in addition to it volition bring some fourth dimension to last adopted in addition to larn an measure way, given the size of Java community some the world.


In Summary prefer TimeUnit.sleep() method if you lot would similar to innovate brusque interruption inwards your computer program in addition to other places where you lot mean value of Thread.sleep(). It non alone improves readability of code but likewise makes you lot familiar amongst java.util.concurrent package, which is cardinal API for concurrent programming inwards Java.

Further Learning
Multithreading in addition to Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Write a Java computer program to create deadlock in addition to create it – Interview Question
  • What is race status inwards Java – an example
  • How to write thread prophylactic code inwards Java
  • Difference betwixt Runnable in addition to Thread class
  • How to job ThreadLocal variable inwards Java – Beware of retentiveness leak
  • How to solve producer consumer job using BlockingQueue inwards Java
  • Belum ada Komentar untuk "Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel