Monday, August 25, 2014

Traverse directories recursively and get the sorted URIs

Here is the utility class which can be used to traverse directories recursively and get the sorted URIs::

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Arrays;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

import java.util.TreeSet;

 

/**

* This class DirectoryTraverser.<br/>

* It returns set of files by traversing directories recursively.

*

* @since 2014

* @author Abhinav Kumar Mishra

*/

public final class DirectoryTraverser {

 

 /**

 * Gets the file URIs. Recursively traverse each directory and uris of files.

 *

 * @param aStartingDir the a starting dir

 * @return the file listing

 * @throws FileNotFoundException the file not found exception

 */

 public static Set<File> getFileUris(final File aStartingDir)

  throws FileNotFoundException {

  checkDirectories(aStartingDir); // throw exception if not valid.

  return getUrisRecursive(aStartingDir);

 }

 

 /**

 * Gets the file uris recursively.

 *

 * @param aStartingDir the a starting dir

 * @return the file listing no sort

 * @throws FileNotFoundException the file not found exception

 */

 private static Set<File> getUrisRecursive(final File aStartingDir)

  throws FileNotFoundException {

  final Set<File> sortedSetOfFiles = new TreeSet<File>();

  final File[] filesAndDirs = aStartingDir.listFiles();

  final List<File> filesDirs = Arrays.asList(filesAndDirs);

  final Iterator<File> filesDirsItr = filesDirs.iterator();

  while (filesDirsItr.hasNext()) {

   final File file = filesDirsItr.next();

   sortedSetOfFiles.add(file); // Add files and directory URIs both

   // If uri is a directory the revisit it recursively.

   if (!file.isFile()) {

    // Call 'getUrisRecursive' to extract uris from directory

    final Set<File> innerSet = getUrisRecursive(file);

    sortedSetOfFiles.addAll(innerSet);

   }

  }

  return sortedSetOfFiles;

 }

 

 /**

 * Checks if is valid directory.<br/>

 * If directory exists then it is valid. If directory is valid then it can

 * be read.

 *

 * @param directoryUri the a directory

 * @throws FileNotFoundException

  */

 private static void checkDirectories(final File directoryUri)

                            throws FileNotFoundException {

  if (directoryUri == null) {

   throw new IllegalArgumentException("Directory should not be null.");

  }if (!directoryUri.exists()) {

    throw new FileNotFoundException("Directory does not exist: "+ directoryUri);

  }if (!directoryUri.isDirectory()) {

   throw new IllegalArgumentException("Is not a directory: "+ directoryUri);

  }if (!directoryUri.canRead()) {

   throw new IllegalArgumentException("Directory cannot be read: "

                       + directoryUri);

  }

 }

 

        public static void main(String[] args) {

  try {

   System.out.println(getFileUris(new File("c:\\intel")));

  } catch (FileNotFoundException e) {

   e.printStackTrace();

  }

 }

}



Output>>
Let directory uri is: C:\Intel

Result:

[c:\intel\ExtremeGraphics,
c:\intel\ExtremeGraphics\CUI,
c:\intel\ExtremeGraphics\CUI\Resource,
c:\intel\Logs,
c:\intel\Logs\IntelChipset.log,
c:\intel\Logs\IntelGFX.log,
c:\intel\Logs\IntelGFXCoin.log]


Sunday, July 27, 2014

Why closing external resources after using it, If GC can take care?


It is strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. Connections are a limited and relatively expensive resource. Any new connection you establish that has exactly the same connection string, will be able to reuse the connection from the pool. If we don't close a DB connection, we get something called a "connection leak" once threshold is reached.


Now come to the GC, GC Cannot guarantee of its execution, neither you can force JVM to run GC on your method (in case you don't close connection.) because GC is a demon thread and hence it has lowest priority. it may execute if it gets the CPU at that time.

So not closing connections and leaving it for GC may result in many problems like web pages hanging, slow page loads, and more.


Also, you should be careful while closing the connections or stream etc. because even though you are closing connection , sometimes it leads to resource leakage if not handled properly. 

Lets take an example: 

public static Properties loadProperties(String fileName) 
throws IOException { 
FileInputStream fis = new FileInputStream(fileName); 
Properties props = new Properties(); 
props.load(fis); 
fis.close(); 
return props; 


In the above example, 'fis' is closed but it still prone to resource leakage. 

How? 
>>It because, if any exception occurred at the call of "load" method only.. method will throw exception but will not release the resource properly. 

Correct way:::: 

public static Properties loadProperties(String fileName) 
throws IOException { 
FileInputStream fis= new FileInputStream(fileName); 
try { 
Properties props = new Properties(); 
props.load(fis); 
return props; 

finally { 
fis.close(); 



And JDK 7 Onwards, you don’t have to be worried about closing resources. You can use TRY,CATCH with resources functionality. 

static String readFirstLineFromFile(String path) throws IOException { 
try (BufferedReader br = 
new BufferedReader(new FileReader(path))) { 
return br.readLine(); 
// Use br…
 }  catch(Exception excp){….}


And one last point... 

Suppose you are using JDBC connection,statement and resultset. Then you should close all 3 resources not only connection. 

And the best way to handle this is>> 

public void someOperation() throws SQLException { 
Statement stmt= null; 
ResultSet rs= null; 
Connection conn= getConnection(); 
try { 
stmt= conn.createStatement(); 
rs= statement.executeQuery("SELECT * FROM EMP"); 
// Use RS 

finally { 
try { 
if (rs!= null) 
rs.close(); 

finally { 
try { 
if (stmt != null) 
stmt.close(); 

finally { 
conn.close(); 



}


Now one more question,  Why to close ResultSet and Statement ??
You must have heard about bad programming practices. So, It is a best programming practice to close ResultSet, Statement along with Connection.

How>> ?

If you are using JDBC connection and not closing ResultSet object it will be automatically closed. So, closing it in finally block will releases this ResultSet object immediately instead of waiting for this to happen when it is automatically closed. Closing ResultSet explicitly enables garbage collector to recollect memory as early as possible because ResultSet object may take lot of memory depending on query.

As per java doc of ResultSet object::

"A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."

Also note that, you can get only one ResultSet object at a time from a Statement. So all execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

So, now Question is why statement should be closed?

As mentioned above the ResultSet will be closed automatically only if you close the Statement object. Not doing so will lead to resource leak.

This is the reason why JDBC API provided close() method for both ResultSet and Statement. These methods are not showpiece is'nt ?


Now, it’s totally depends on you whether you are writing a good quality code or not.

Saturday, July 26, 2014

Ways to implement Threads in Java.

You can create thread in 4 ways... 

1- Using anonymous class implementation of Thread. 
2- By Implementing Runnable Interface. 
3- By extending the Thread class itself. 

1- Using anonymous class implementation of Thread:

         Using Anonymous Thread>>> 

         public class CreateMultiThread {
            public static void main(String[] args) {
              Thread t1 = new Thread ("First"){
                     @Override
                     public void run() {
                           for (int i = 0; i < 4; i++) {
                                  System.out.println(getName()+" : "+i);
                           }
                     }
              };
             
              Thread t2 = new Thread ("second"){
                     @Override
                     public void run() {
                           for (int i = 0; i < 4; i++) {
                                  System.out.println(getName()+" : "+i);
                           }
                     }
              };
             
              t1.start();
              t2.start();
              System.out.println("In Main()");
         }
    }

    OUTPUT:
      In Main()
      First : 0
      second : 0
      First : 1
      second : 1
      First : 2
      second : 2
      First : 3
      second : 3

Using Anonymous Runnable>>> 
    
 public class CreateMultiThread {
   public static void main(String[] args) { 
      Runnable runnable= new Runnable() {
   @Override
   public void run() {
    for (int i = 0; i < 4; i++) {
     System.out.println(i);
    }
   }
       };
 
     Thread t1 = new Thread(runnable,"First");
     Thread t2 = new Thread(runnable,"Second");
     t1.start();
     System.out.println("Thread: "+t1.getName());
     t2.start();
     System.out.println("Thread: "+t2.getName());
     System.out.println("In Main()");

    }
}

OUTPUT>>
      Thread: First
        0
        1
        2
        3
        0
        1
        2
        3
        Thread: Second
        In Main()


    2- By Implementing Runnable Interface:
      
        class ThreadUsingRunnable implements Runnable {
 private Thread t;
 private String name;

 ThreadUsingRunnable(String name) {
  this.name = name;
  t = new Thread(this, name);
  System.out.println("Child Thread:: " + t);
  t.start();
               }

 public void run() {
  for (int i = 0; i < 4; i++) {
   System.out.println(name + ": " + i);
  }
 }
     }
     
 //Testing the thread
 public class CreateMultiThread {
 public static void main(String[] args) {
 
  new ThreadUsingRunnable("first");
  new ThreadUsingRunnable("second");
  new ThreadUsingRunnable("third");
  try {
   Thread.sleep(1000);
  } catch (InterruptedException ee) {
   System.out.println("Main Intrrupted!!");
  }
  System.out.println("Main Exiting!!");
 }
   }
   
    OUTPUT>>
     Child Thread:: Thread[first,5,main]
     Child Thread:: Thread[second,5,main]
     first: 0
     first: 1
     Child Thread:: Thread[third,5,main]
     first: 2
     second: 0
     first: 3
     second: 1
     second: 2
     second: 3
      third: 0
      third: 1
      third: 2
      third: 3
      Main Exiting!!
   
    
    3By extending Thread class itself:

       class ThreadUsingThreadClass extends Thread {
 private String name;
 ThreadUsingThreadClass(String name) {
  super(name);
  this.name = name;
  System.out.println("Child Thread:: " + this);
  start();
 }

 public void run() {
  for (int i = 0; i < 4; i++) {
   System.out.println(name + ": " + i);
  }
 }
     }

 //Testing the thread
 public class CreateMultiThread {
      public static void main(String[] args) {
  new ThreadUsingThreadClass("first");
  new ThreadUsingThreadClass("second");
  new ThreadUsingThreadClass("third");
  try {
   Thread.sleep(1000);
  } catch (InterruptedException ee) {
   System.out.println("Main Intrrupted!!");
  }
  System.out.println("Main Exiting!!");
          }
      }
  
     OUTPUT>>
      Child Thread:: Thread[first,5,main]
      Child Thread:: Thread[second,5,main]
      first: 0
      first: 1
      first: 2
      first: 3
     Child Thread:: Thread[third,5,main]
     second: 0
     second: 1
     second: 2
     second: 3
     third: 0
      third: 1
      third: 2
      third: 3
      Main Exiting!!


Which method is best for implementing Threads::

1st Reason>>

Creating your thread implementation class by extending the Thread class makes it heavy, as it inherits all the properties of Thread class.
While implementing Runnable , our motive is to provide the implementation of run() method not the actual Thread class. As we all know Thread class also implement Runnable to get the run() method. Hence the object implementing Runnable will have run () method and will be a lightweight object.


2nd Reason>>

In Java we can extend only one class at a time, so if we extend Thread class we can’t extend any other class while by implementing Runnable interface we still have that option to extend some other class. 

Hence, create your thread implementation by extending the Thread class only when you want to override the some behavior of Thread class.


Leave your comments/suggestions below. Otherwise the next time :)