Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips

Advertisement

Masukkan script iklan 970x90px

Prefer Timeunit Slumber Over Thread.Sleep - Coffee Coding Tips

Kamis, 23 Juli 2020

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

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

Thread.sleep(2400000);


By simply having a cursory glance, tin strength out y'all figure out how long electrical flow Thread volition wait ? Some of y'all may hold upwards but its hardly readable for many Java programmer too y'all require to convert milliseconds farther into seconds too and thence into minutes. Let's bring a await on some other representative of Thread.sleep() method which is slightly to a greater extent than readable than previous example.

Thread.sleep(4*60*1000);

This is much improve than previous i but withal its non perfect too until y'all are aware that slumber times are inwards millisecond its non slow to approximate that electrical flow Thread volition hold off for 4 minutes. TimeUnit flat resolves this final result yesteryear providing indicator for DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS too NANOSECONDS. java.util.concurrent.TimeUnit is perfect representative of powerful Java Enum. All TimeUnit are Enum instances. Let's meet how to slumber Thread for 4 minutes using TimeUnit :

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

Similarly y'all tin strength out innovate pauses on seconds, minutes too hour level. By looking this code y'all tin strength out 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 too throws InterruptedException. You tin strength out too banking concern fit JDK code to verify that. Here is a sample code representative 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 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 too render convenient method to convert fourth dimension into unlike Unit. For representative if y'all desire to convert seconds into milliseconds than y'all tin strength out exercise next code :

TimeUnit.SECONDS.toMillis(44)

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



TimeUnit vs Thread.sleep()

Java programmer knows close it too yesteryear looking Thread.sleep() they come upwards to know that Thread is going to pause. This is non truthful amongst TimeUnit class, amongst ii argue start its non real pop at to the lowest degree compare to Thread.sleep() too 2nd it's non inwards Thread class, much similar wait too notify which are too non inwards Thread class.. Anyway none of these are big issues too it volition bring some fourth dimension to hold upwards adopted too drib dead an criterion way, given the size of Java community simply about the world.


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

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