Posts

Showing posts with the label tips

Java - One liner to Configure Logging

Often while writing some quick test or doing a prototype, we want to use logging. But we do not want to spend any time writing a properties file and doing the whole setup. However there is a quick way to get log4j ready to use in a single line. Log4j provides a BasicConfigurator which can be used to quickly configure the logging. Usage Example - public class LoggingOneLiner1 { private static final Logger logger = Logger .getLogger(LoggingOneLiner1.class); public static void main(String[] args) { // Configure the logging - this does the whole setup BasicConfigurator.configure(); // Optional Step - change the logging level to INFO from default DEBUG Logger.getRootLogger().setLevel(Level.INFO); logger.info("Its nice to to be able to configure logging in one line"); logger.debug("I like quick and dirty java tricks"); } } From the api docs of log4j - The invocation of the   BasicConfigurator.configure   method creates a rather simpl...

Improving readability using TimeUnit sleep

All of us have seen the following idiom  numerous times in java code. //Sleep for 6 minutes Thread.sleep(6*60*1000); However the above is not readable. When someone is writing code, he has to perform the conversion to milliseconds. While trying to understand the code also, someone has to perform the transformation from milliseconds to familiar seconds and minutes. java.util.concurrent .TimeUnit class also provides mechanism to sleep which circumvents the above difficulties. Following is an example of sleep using TimeUnit. //Sleep for 6 minutes TimeUnit.MINUTES.sleep(6); //Sleep for 10 seconds TimeUnit.SECONDS.sleep(10); //Sleep for 2 hours TimeUnit.HOURS.sleep(2); TimeUnit supports following time units for sleep. DAYS HOURS MICROSECONDS MILLISECONDS MINUTES NANOSECONDS  SECONDS Internally TimeUnit also invokes Thread.sleep() for sleeping. Following is the code used by sleep() method in TimeUnit public void sleep(long timeout) throws Interrupte...