Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips

What is TimeUnit inwards Java
TimeUnit
inwards Java is a degree on java.util.concurrent package, introduced inwards Java v along amongst CountDownLatch, CyclicBarrier, Semaphore together with several other concurrent utilities. TimeUnit provides a human readable version of Thread.sleep() method which tin endure used inwards house of former. From long fourth dimension Thread's sleep() method is touchstone agency to interruption a Thread inwards Java together with almost every Java programmer is familiar amongst that. In fact, slumber method itself is a real pop together with has appeared on many Java interviews. The divergence betwixt hold off together with sleep is i of the tough Java questions to answer. If yous guide maintain used Thread.sleep() earlier together with I am certain yous do, yous mightiness endure familiar amongst a fact similar it's a static method, it doesn't unloose the lock when pausing Thread together with it throws InterruptedException

But what many of us doesn't reckon a potential consequence is readability. Thread.sleep() is an overloaded method together with bring long millisecond together with long nanosecond, which makes it difficult for programmers to discovery out just how many seconds, minutes, hours or solar daytime electrical current Thread is sleeping. Look at below illustration of Thread's sleep() method:

Thread.sleep(2400000);


By only having a cursory glance, tin yous figure out how long electrical current Thread volition wait ? Some of yous may endure but its hardly readable for many Java programmer together with yous involve to convert milliseconds farther into seconds together with thus into minutes. Let's bring a await on some other illustration 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 i but nonetheless its non perfect together with until yous are aware that slumber times are inwards millisecond its non tardily to approximate that electrical current Thread volition hold off for iv minutes. TimeUnit degree resolves this consequence past times providing indicator for DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS together with NANOSECONDS. java.util.concurrent.TimeUnit is perfect illustration of powerful Java Enum. All TimeUnit are Enum instances. Let's run across how to slumber Thread for iv minutes using TimeUnit :

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

Similarly yous tin innovate pauses on seconds, minutes together with hour level. By looking this code yous tin discovery 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 together with throws InterruptedException. You tin too cheque JDK code to verify that. Here is a sample code illustration which demonstrate how to exercise TimeUnit's sleep() method inwards Java.

/**
 *
 * Java plan to demonstrate how to exercise 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 iv minutes using Thread.sleep()");
        Thread.sleep(4 * 60 * 1000);
        System.out.println("Sleeping for iv 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 too furnish convenient method to convert fourth dimension into dissimilar Unit. For illustration if yous desire to convert seconds into milliseconds than yous tin exercise next code :

TimeUnit.SECONDS.toMillis(44)

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



TimeUnit vs Thread.sleep()

Java programmer knows almost it together with past times looking Thread.sleep() they come upward to know that Thread is going to pause. This is non truthful amongst TimeUnit class, amongst ii argue starting fourth dimension its non real pop at to the lowest degree compare to Thread.sleep() together with 2nd it's non inwards Thread class, much similar wait together with notify which are too non inwards Thread class.. Anyway none of these are big issues together with it volition bring some fourth dimension to endure adopted together with drib dead an touchstone way, given the size of Java community unopen to the world.


In Summary prefer TimeUnit.sleep() method if yous would similar to innovate brusk interruption inwards your plan together with other places where yous intend of Thread.sleep(). It non solely improves readability of code but too makes yous familiar amongst java.util.concurrent package, which is primal API for concurrent programming inwards Java.

Further Learning
Multithreading together with Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Write a Java plan to create deadlock together with ready it – Interview Question
  • What is race status inwards Java – an example
  • How to write thread rubber code inwards Java
  • Difference betwixt Runnable together with Thread class
  • How to exercise ThreadLocal variable inwards Java – Beware of retentivity leak
  • How to solve producer consumer work using BlockingQueue inwards Java

  • Sumber https://javarevisited.blogspot.com/

    0 Response to "Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel