Sunday 19 May 2013

ARM- Automatic resource management in Java7 an example tutorial

ARM automatic resource management is  another attractive features of Java 7 and project coin. As name itself implies that now JVM is going to be handling all the external resource and make programmer free to bother about resource management.  If my java programmers use any external resources like file, printer or any devices to close after my program execution complete. Normally we close the resources which we have open in beginning of our program or we decide that if program finish normally how to manage the resource or if our program finish abnormally how to close the resource.

ARM- Automatic resource management in Java

automatic resource management (ARM) in java jdk7Earlier this things or resource management are achieved by try {} catch {} finally block we need to declare resource variable outside of try block and in catch or finally we use this variables for achieving normal execution of program. This JDK7 tutorial is in continuation of my earlier tutorial How to code with multi-cache exception in JDK7 and How to use String in Switch case on JDK7

Example of resource management in java before JDK7

Here is an example of how we used to do handle resource management before automatic resource management (ARM) feature was made available.
FileInputStream stockQuoteReader= null;
      FileOutputStream stockQuoteWriter = null;
      try {
        stockQuoteReader = new FileInputStream("StockQuotes.txt");
        stockQuoteWriter = new FileOutputStream("StockQuotes.txt");
        int var;
        while (var = stockQuoteReader.read()) != -1)
          stockQuoteWriter.write(var);
      } finally {
        if (stockQuoteReader!= null)
          stockQuoteReader.close();
        if (stockQuoteWriter!= null)
          stockQuoteWriter.close();
      }

But with java 1.7 we manage this thing very easily by try with resource block where inside try we mange this external resources.


Signature of Automatic Resource Management (ARM)

Signature is try(resource1;resource2){}after final resource ;semicolon is not allowed and the resource should be like var=expression type and bydefault all the resources are final  type.

What has been added in API for Automatic Resource Management

java.lang.AutoCloseable, interface has been added in API which contains single method close() throws Exception    this interface is a parent of java.io.closeable interface so all the input and output devices inherit this property.


Example of Automatic Resource Management (ARM) in JDK7

Here is example of automatic resource management with JDK 1.7 source base. Please make sure you run this with java source 1.7 otherwise you will get compilation error.



FileInputStream stockQuoteReader = new FileInputStream("StockQuotes.txt");
FileOutputStream stockQuoteWriter = new FileOutputStream("StockQuotes.txt")
      int var;
      while((var= stockQuoteReader.read()) != -1 )
            stockQuoteWriter.write();
  }


In this code inside try we have declare two file stream one is input file we are reading from one file and writing to another file. After the whole process both streams will be closed automatically either the code has been executed normally or not that means stockQuoteReader.close() and stockQuoteWriter.close() called automatically which is the best part of ARM.
If we compare this with earlier example   then if any exception occur during input file closing i.e. stockQuoteReader.close() , stockQuoteWriter.close() will never get executed so our code terminated abnormally.


Some important points which needs to be keep in mind when use ARM

§          Whatever resource we are using should be subtypes of AutoCloseable other wise will get compile time error.

§          The resources which we are using are closed in reverse order means stockQuoteWriter.close() will be called first then stockQuoteReader.close().
That’s all on new automatic resource management (ARM) feature on JDK7, some how it address the cluttering of code due to checked exception handling and code duplication on several exception cache block.


Related tutorials in Java

How to deal with OutOfMemoryError in Java

How to solve ClassNotFoundException in Java

How to solve UnSupportedClassVersionError in Java

Difference between ClassNotFoundException and NoClassDefFoundError

Difference between String, StringBuffer and StringBuilder in Java

Difference between Comparator and Comparable with Example

Difference between hashtable and hashmap in java

10 example of enum in java

How Hash Map works in Java?

Please share with your friends if like this article

10 Object Oriented Design Principles Java Programmer should know

Object Oriented Design Principles are core of OOPS programming, but I have seen most of Java programmer chasing design patterns like Singleton pattern , Decorator pattern or Observer pattern , and not putting enough attention on learning Object oriented analysis and design. It's important to learn basics of Object oriented programming like Abstraction, Encapsulation, Polymorphism and Inheritance, but same time, it's equally important to know these design principles, to create clean and modular design. I have regularly seen Java programmers and developers of various experience level, who either doesn't heard about these OOPS and SOLID design principle, or simply doesn't know what benefits a particular design principle offers, or how to use these design principle in coding.

Bottom line is, always strive for highly cohesive and loosely couple solution, code or design. Looking open source code from Apache and Sun are good examples of learning Java and OOPS design principles. They show us,  how design principles should be used in coding and Java programs. Java Development Kit follows several design principle like Factory Pattern in BorderFactory class,  Singleton pattern in Runtime class, Decorator pattern on various java.io classes. By the way if you really interested more on Java coding practices,  read Effective Java by Joshua Bloch , a gem by the guy who wrote Java API. My another personal favorite on object oriented design pattern is,  Head First Design Pattern by Kathy Sierra and others and Head First Object Oriented Analysis and Design . These books helps a lot to write better code, taking full advantage of various Object oriented and SOLID design principles.


Object oriented design principles and pattern in Java programmingThough best way of learning any design principle or pattern is real world example and understanding the consequences of violating that design principle, subject of this article is Introducing Object oriented design principles for Java Programmers, who are either not exposed to it or in learning phase. I personally think each of these OOPS and SOLID design principle need an article to explain them clearly, and I will definitely try to do that here, but for now just get yourself ready for quick bike ride on design principle town :)

DRY (Don't repeat yourself)

Our first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important  not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.

Encapsulate What Changes

Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.

Open Closed Design Principle

Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful SOLID design principle, which prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. By the way, Open Closed principle is "O" from SOLID acronym.

Single Responsibility Principle (SRP)

Single Responsibility Principle is another SOLID design principle, and represent  "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java  it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality,  which require another round of testing to avoid any surprise on production environment.

Dependency Injection or Inversion principle

Don't ask for dependency it will be provided to you by framework. This has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI framework is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that.There are multiple ways to  implemented Dependency injection like using  byte code instrumentation which some AOP (Aspect Oriented programming) framework like AspectJ does or by using proxies just like used in Spring. See this example of IOC and DI design pattern to learn more about this SOLID design principle. It represent "D" on SOLID acronym.

Favor Composition over Inheritance

Always favor composition over inheritance ,if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.

Liskov Substitution Principle (LSP)

According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent  "L" on SOLID acronym.

Interface Segregation principle (ISP)

Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement.

Programming for Interface not implementation

Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.

Don't do all stuff  by yourself,  delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.

All these object oriented design principle helps you write flexible and better code by striving high cohesion and low coupling. Theory is first step, but what is most important is to develop ability to find out when to apply these design principle. Find out, whether we are violating any design principle and compromising flexibility of code, but again as nothing is perfect in this world, don't always try to solve problem with design patterns and design principle they are mostly for large enterprise project which has longer maintenance cycle.
Other Java tutorial you may like

Why String is immutable in Java

Why wait and notify methods are defined in Object Class

Use Memory Mapped IO for high performance in Java

How SubString method works in Java

LDAP authentication against active directory using Spring security

10 Example of display tag in JSP Servlet

Please share with your friends if like this article

MySql Tutorial : mysqldump utility in mysql

MySql Tutorial : mysqldump utility in mysql

The mysqldump client is a backup program o It can be used to dump a database or a collection of databases for backup or transfer to another SQL server (not necessarily a MySQL server). The dump typically contains SQL statements to create the table, populate it, or both. However, mysqldump can also be used to generate files in CSV, other delimited text, or XML format.


To take dump of a mysql table use below command
-------------------------------------------------------
~/mysql/bin/mysqldump -u root  database_name ORDERS > orders.txt

1.  command to dumb  only tables definitions , not the data “ use –d command”  if path is not set then you need to run that command from mysql/bin directory

./mysqldump -d -u root database_name  ORDERS , CLIENTS , COMPANY  > ~/tmp/test.database.sql

2. Command to recreate table from that file

mysql -u root database_name < ~/tmp/test.database.sql


hope this would be useful. if you have not read my other MySQL command tutorials , you can see it here

MySQL tutorial and commands part 2
MySQL tutorial and commands part 3
MySql Tutorial : mysqldump utility in mysql
MySQL tutorial and commands Part 1

Difference between truncate and delete in SQL

Basic and Advanced SELECT command example

How to manage transaction in MySQL




Please share with your friends if like this article

How to get and set default Character encoding or Charset in Java

Default Character encoding in Java or charset is the character encoding used by JVM to convert bytes into Strings or characters when you don't define java system property "file.encoding". Java gets character encoding by calling System.getProperty("file.encoding","UTF-8") at the time of JVM start-up. So if Java doesn't get any file.encoding attribute it uses "UTF-8" character encoding for all practical purpose e.g. on String.getBytes() or Charset.defaultCharSet().

Most important point to remember is that Java caches character encoding or value of system property "file.encoding" in most of its core classes like InputStreamReader which needs character encoding after JVM started. so if you change system property "file.encoding" programatically you don't see desired effect and that's why you should always work with your own character encoding provided to your application and if its need to be set than set character encoding or charset while you start JVM. In this Java tutorial we will see couple of different way by which we can set default character encoding or charset of Java and how to retrieve value of charset inside java program.

Default Character encoding or Charset in Java

This article is in continuation of my post on Java String like Why String is immutable in Java or How SubString method works in java. If you haven’t read those you may find interesting.

What is character encoding in Java

default character encoding or charset in java exampleFor those who are not very familiar with character encoding or char-set in Java here is a layman's introduction "since every data in computer is represented in bytes and Strings are essentially collection of charaters, so to convert bytes into character JVM needs to know which combination of byte represent which character and this is what character encoding tells JVM. Since there are many languages in world other than English like Hindi, Mandarin, Japanese Kanji etc and so many characters, same combination of bytes can represent different characters in different character encoding and that's why using correct character encoding is must while converting bytes into String in Java".

How to get Default character encoding in Java ?

There are multiple ways to get default character encoding in Java like by using system property “file.encoding” or by using java.nio.CharSet class. You can choose whatever suits your need. Let’s see them in detail.
1) "file.encoding" system property
Easiest way to get default character encoding in Java is to call System.getProperty("file.encoding"), which will return default character encoding if JVM started with -Dfile.encoding property or program has not called System.setProperty("file.encoding, encoding). in later case it may just give value of that system property while various
java.nio.Charset provides a convenient static method Charset.defaultCharset() which returns default character encoding in Java. Check example of getting default char encoding in java using Charset in code section.
3) by using Code InputStreamReader.getEncoding()
This is kind of shortcut where you use default constructor of InputStreamReader and than later gets which character encoding it has used by calling reader.getEncoding() . See the code example of how to get default character encoding using InputStreamReader.getEncoding() method in code section.

How to set Default character encoding in Java ?

Just like different ways of getting default character encoding or charset in Java there are many ways to set default charset in Java. Here are some of  the way:
1. Using System property "file.encoding"
by providing file.encoding system property when JVM starts e.g. java -Dfile.encoding="UTF-8"  HelloWorld.
2. Using Environment variable "JAVA_TOOLS_OPTIONS"
If by anyway you don't have control how JVM starts up may be JVM is starting through some scripts which doesn't provide any way to accept system properties. you can set environment variable JAVA_TOOL_OPTIONS to -Dfile.encoding="UTF-16" or any other character encoding and it will picked up any JVM starts in your windows machine. JVM will also print "Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF16" on console to indicate that it has picked JAVA_TOOS_OPTIONS. here is example of setting default character encoding using JAVA_TOOLS_OPTIONS
test@system:~/java java HelloWorld
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF16

You can also check my post 10 JVM Options developer should know for more on JVM Options

Code Example to Get and Set Default Character Encoding Java

Here is code example of getting and setting default character encoding in Java:

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class CharacterEncodingExample {
    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        String defaultCharacterEncoding = System.getProperty("file.encoding");
        System.out.println("defaultCharacterEncoding by property: " + defaultCharacterEncoding);
        System.out.println("defaultCharacterEncoding by code: " + getDefaultCharEncoding());
        System.out.println("defaultCharacterEncoding by charSet: " + Charset.defaultCharset());
      
        System.setProperty("file.encoding", "UTF-16");
      
        System.out.println("defaultCharacterEncoding by property after updating file.encoding : " + System.getProperty("file.encoding"));
        System.out.println("defaultCharacterEncoding by code after updating file.encoding : " + getDefaultCharEncoding());
        System.out.println("defaultCharacterEncoding by java.nio.Charset after updating file.encoding : " + Charset.defaultCharset());
    public static String getDefaultCharEncoding(){
        byte [] bArray = {'w'};
        InputStream is = new ByteArrayInputStream(bArray);
        InputStreamReader reader = new InputStreamReader(is);
        String defaultCharacterEncoding = reader.getEncoding();
        return defaultCharacterEncoding;
defaultCharacterEncoding by property: UTF-8
defaultCharacterEncoding by code: UTF8
defaultCharacterEncoding by charSet: UTF-8
defaultCharacterEncoding by property after updating file.encoding : UTF-16
defaultCharacterEncoding by code after updating file.encoding : UTF8
defaultCharacterEncoding by java.nio.Charset after updating file.encoding : UTF-8

Important points to note:
1) JVM caches value of default character encoding once JVM starts and so is the case for default constructors of InputStreamReader and other core Java classes. So calling System.setProperty("file.encoding" , "UTF-16") may not have desire effect.
2) Always work with your own character encoding if you can, that is more accurate and precise way of converting bytes to Strings.
That’s all on how to get default character encoding in Java and how to set it. This becomes more important when you are 
writing international application which supports multiple languages. I indeed come across character encoding issues while 
writing reports in  kanji (Japanese) language which I plan to share in another post, but good knowledge of Character 
encoding like UTF-8, UTF-16 or ISO-8859-5 and how Java supports Character Encoding in 
String will certainly help.
Other Java tutorials you may like

Why Multiple inheritance in not supported in Java

How to write Thread-Safe Code in Java

How to Convert String to Double in Java

Difference between Comparator and Comparator in java

How to override equals method in Java

Why main is declared static in Java

10 best practices to follow while writing code comments

Please share with your friends if like this article

ThreadLocal in Java - Example Program and Tutorial

ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application. In this Java ThreadLocal tutorial we will see important points about ThreadLocal in Java, when to use ThreadLocal in Java and a simple Example of ThreadLocal in Java program.


When to use ThreadLocal in Java

ThreadLocal Code Example in JavaMany Java Programmer question where to use ThreadLocal in Java and some even argue benefit of ThreadLocal variable, but ThreadLocal has many genuine use cases and that's why its added in to standard Java Platform Library. I agree though until you are not in concurrent programming, you will rarely use ThreadLocal. below are some well know usage of ThreadLocal class in Java:

1) ThreadLocal are fantastic to implement Per Thread Singleton classes or per thread context information like transaction id.

2) You can wrap any non Thread Safe object in ThreadLocal and suddenly its uses becomes Thread-safe, as its only being used by Thread Safe. One of the classic example of ThreadLocal is sharing SimpleDateForamt. Since SimpleDateFormat is not thread safe, having a global formatter may not work but having per Thread formatter will certainly work.

3) ThreadLocal provides another way to extend Thread. If you want to preserve or carry information from one method call to another you can carry it by using ThreadLocal. This can provide immense flexibility as you don't need to modify any method.

On basic level ThreadLocal provides Thread Confinement which is extension of local variable. while local variable only accessible on block they are declared, ThreadLocal are visible only in Single Thread. No two Thread can see each others ThreadLocal variable. Real Life example of ThreadLocal are in J2EE application servers which uses java ThreadLocal variable to keep track of transaction and security Context. It makes lot of sense to share heavy object like Database Connection as ThreadLocal in order to avoid excessive creation and cost of locking in case of sharing global instance.

Java ThreadLocal Example – Code

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author
 */

public class ThreadLocalTest {

    public static void main(String args[]) throws IOException {
        Thread t1 = new Thread(new Task());  
        Thread t2 = new Thread( new Task());
     
        t1.start();
        t2.start();      
     
    }
   
    /*
     * Thread safe format method because every thread will use its own DateFormat
     */

    public static String threadSafeFormat(Date date){
        DateFormat formatter = PerThreadFormatter.getDateFormatter();
        return formatter.format(date);
    }
   
}


/*
 * Thread Safe implementation of SimpleDateFormat
 * Each Thread will get its own instance of SimpleDateFormat which will not be shared between other threads. *
 */

class PerThreadFormatter {

    private static final ThreadLocal<SimpleDateFormat> dateFormatHolder = new ThreadLocal<SimpleDateFormat>() {

        /*
         * initialValue() is called
         */

        @Override
        protected SimpleDateFormat initialValue() {
            System.out.println("Creating SimpleDateFormat for Thread : " + Thread.currentThread().getName());
            return new SimpleDateFormat("dd/MM/yyyy");
        }
    };

    /*
     * Every time there is a call for DateFormat, ThreadLocal will return calling
     * Thread's copy of SimpleDateFormat
     */

    public static DateFormat getDateFormatter() {
        return dateFormatHolder.get();
    }
}

class Task implements Runnable{
   
    @Override
    public void run() {
        for(int i=0; i<2; i++){
            System.out.println("Thread: " + Thread.currentThread().getName() + " Formatted Date: " + ThreadLocalTest.threadSafeFormat(new Date()) );
        }      
    }
}

Output:
Creating SimpleDateFormat for Thread : Thread-0
Creating SimpleDateFormat for Thread : Thread-1
Thread: Thread-1 Formatted Date: 30/05/2012
Thread: Thread-1 Formatted Date: 30/05/2012
Thread: Thread-0 Formatted Date: 30/05/2012
Thread: Thread-0 Formatted Date: 30/05/2012

If you look the output of above program than you will find that when different thread calls getFormatter() method of ThreadLocal class than its call its initialValue() method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is not shared between thread and essentially local to the thread which creates its our threadSafFormat() method is completely thread-safe.

Important points on Java ThreadLocal Class

1. ThreadLocal in Java is introduced on JDK 1.2 but it later generified in JDK 1.4 to introduce type safety on ThreadLocal variable.
2. ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.

3. Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn't have any other live references.

4. ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread.
We saw how ThreadLocal in Java opens another avenue for thread-safety. Though concept of thread-safety by confining object to Thread is there from JDK 1.0 and many programmer has there own custom ThreadLocal classes, having ThreadLocal in Java API makes it a lot more easy and standard. Think about ThreadLocal variable while designing concurrency in your application. Don't misunderstood that ThreadLocal is alternative of Synchronization, it all depends upon design. If design allows each thread to have there own copy of object than ThreadLocal is there to use.
Other Java tutorials on Threading you may find useful

Difference between Runnable and Thread Class

Why wait and notify methods are declared in Object Class?

Difference between ConcurrentHashMap and Hashtable in Java

Why wait and notify needs to called from Synchronized Context?

Difference between invokeAndWait and InvokeLater in java Swing.

Difference between wait and sleep in Java

How to fix Race conditions in Java with Example

Please share with your friends if like this article