Sunday, January 6, 2013

Extract a list of filtered files in Java

Sometimes, we need to get a list of files exist within a directory as per our criteria like filename, file extension, last modified date or other attributes. It reduces the overhead to filter them after getting the list using our code. To achieve this, Java provides an interface - FileFilter which has a single method prototype as boolean accept(File file). To apply our filtering criteria, we have to override this method and if our logic returns true for a file then only the file will be included in the list otherwise not. 

Example :- 

import java.io.*;
import java.util.*;
 
public class FilteredFileList {
    public static File[] getFilteredFileList(File folder, final String filenameFilter, Date lastModifiedDateFilter) {
        File[] listOfFiles = folder.listFiles(new FileFilter(){
                                public boolean accept(File file) {
                                    //file is the object against which we are applying our logic.
                                    //You can put your logic using filenameFilter and check whether
                                    //the file's name comes under your criteria or not.
                                    //To check against the lastmodified date you can use lastModifiedDateFilter.
                                    return true;
                                }});
        return listOfFiles;
    }
}

JDBC Connection in Java

JDBC (Java DataBase Connectivity) is an API for the Java programming language through which the databse can be accessed using methods for querying and updating data.


Example :- 

import java.sql.*;
 
public class ConnectionInfo {
 
    public Connection getConnection() {
        Connection conn = null;
        // the below properties should be read from a properties file based on the Database used
        String url = "jdbc:mysql://localhost:3306/"; // url = jdbc:[subprotocol]://[hostname]:[portnumber]/
        String dbName = "jdbctutorial"; // database name
        String driver = "com.mysql.jdbc.Driver"; //Driver class name
        String username = "root"; // username
        String password = "root"; // password
        try {
          Class.forName(driver); // Dynamic loading based on database used.
          conn = DriverManager.getConnection(url + dbName, username, password);
          System.out.println("Connection Established");
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            return conn;
        }
    }
 
    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Java Multithreading


Process can be further divided into small tasks which refer as a Thread. If two or more tasks of a process executes concurrently, then this scenario refers as aMultithreading environment. Every thread has it's own independent path of execution. In java, there are two ways to implement multithreading -

Through implementation of Runnable interface - To create a thread, we can implement Runnable interface. This interface has a single run() method declaration, so we have to override that method. Actually, in this approach, we write a wrapper over Thread class. The objects of the class which implements Runnable interface, work as a thread of the program and run on their own execution paths.

Example :- 
public class RunnableExample implements Runnable {
    private Thread thread;
    public RunnableExample(String name) {
        //here we pass the reference whose run method should be called.
        thread = new Thread(this, name);
        //creating thread
        thread.start();
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class RunnableMain {
    public static void main(String[] args) {
        //Creating three objects
        Runnable run1 = new RunnableExample("Thread-1");
        Runnable run2 = new RunnableExample("Thread-2");
        Runnable run3 = new RunnableExample("Thread-3");
    }
}



2. Using Thread class extension - This is another approach of thread creation. But, it restricts the class to extend other classes (if required). In this approach, we extend our class to Thread class so that it's objects work as threads and run on their own separate execution paths.

Here is the sample code -
public class ThreadExample extends Thread {
 
    public ThreadExample(String name) {
        super(name);
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class ThreadMain {
    public static void main(String[] args) {
        //Creating three objects
        Thread t1 = new ThreadExample("Thread-1");
        Thread t2 = new ThreadExample("Thread-2");
        Thread t3 = new ThreadExample("Thread-3");
        creating threads
        t1.start();
        t2.start();
        t3.start();
    }
}

Recursion

Recursion is one of the interesting topic. The problems, which can be implemented using loops, can be implemented with Recursion as well. But, most of us go with the looping solution. Today, I am going to set some light on how the same logic can be implemented using recursion. If we could derive a mathematical function for these type of problems, the implementation will be more easier. Lets understand it through some examples.

Example 1 : Factorial 
The factorial of a non-negative number is the multiplication of all the positive integers which are less than or equal to the number.

Suppose fact(n) is a function of n, where x is non-negative integer value. Hence 

fact(0) = fact(1) = 1
fact(2) = 2 * fact(1) = 2
fact(3) = 3 * fact(2) = 6
...
...
... 
fact(n) = n * fact(n-1)

So, the logic would be - If the value of n is 0 or 1 return 1, else return multiplication of n and value of function for (n-1).


int fact(int num) {
    if(num == 0 || num == 1)
        return 1;
    else
        return num * fact (num - 1);
}
Example 2 : Fibonacci Series 
The Fibonacci series is a sequence of integers whose first and second terms are 0 and 1 respectively and  each subsequent term is the sum of the previous two terms. Like - 0, 1, 1, 2, 3, 5, 8, 13, 21, .....

Suppose fibo(n) is a function of n which returns the term n of the fibonacci series and where n > 0 -

fibo(1) = 0
fibo(2) = 1
fibo(3) = fibo(1) + fibo(2) = 1
fibo(4) = fibo(2) + fibo(3) = 2
fibo(5) = fibo(3) + fibo(4) = 3
...
...
...
fibo(n) = fibo(n-2) + fibo(n-1)

So, the logic would be - If the value of n is 1 or 2 return (n-1), else return the addition of value of function for (n-2) and function for (n-1) .

int fibo(int num) {
    if(num == 1 || num == 2)
        return (num - 1);
    else
        return fibo(num - 2) + fibo(num - 1);
}

Singleton design pattern

The Singleton class means whose only one instance can be created. To make the class Singleton, we should restrict the ways through which the objects can be created. The object can be created in the following ways -
  1. Using new operator
  2. Using newInstance() method  (by Dynamic loading of class).
  3. Through Serialization/Deserialization
  4. Through Cloning
To restrict the ways of object  creation, we should take care of the following points -
  1. The Constructer must be private so that static (using new operator) and dynamic (using newInstance() method) creation of object does not get supported.
  2. Static field as object of the Singleton class should be declared within that class. In getInstance() method, it should be checked whether the static object has been instantiated or not. If not, then instantiate and return it.
  3. The method getInstance() must be Static and Synchronized. Static, so it can be accessed through the class name. Synchronized, because it should be thread-safe.
  4. The class must implement the Externalizable interface and override thewriteExternal() and readExternal() methods such that serialization/deserialization should not be supported.
  5. The class must override clone() method so that another object could not get created.

import java.io.*;
 
//Implement Externalizable interface to avoid object creation through Deserialization.
public class SingletonExample implements Externalizable {
    //make a static object
    private static SingletonExample g_instance;
 
    //make the construct as provate to hide it from outer world.
    private SingletonExample() {
        //do nothing
    }
 
    //make this static method as synchronized for thread-safe model.
    public synchronized static SingletonExample getInstance() {
        if (g_instance == null)             
            g_instance = new SingletonExample();
        return g_instance;
    }
     
    //override method and throw exception to avoid serialization     
    public void writeExternal(ObjectOutput out) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Serialization is not supported.");
    }     
 
    //override method and throw exception to avoid deserialization
    public void readExternal(ObjectInput in) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Deserialization is not supported.");
    }         
 
    //override method to avoid object cloning
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning not allowed");
    } 
}
 
//As the methods writeExternal and readExternal throws IOException, hence we have to extend to create our own Exception.
class SerializationNotAllowedException extends IOException {
    public SerializationNotAllowedException(String message) {
        super(message);
    }
}

Static and Non Static Synchronized Methods



Static Method Call - When we make a call to a static method (either directly from class or any object of that class), the Class object of that Class involves in that call. Every Class has only one Class object.

Non-static Call -  When we call a non-static method (always from an object of that class), it works for that object only (which is of that class only). A class can have as many objects (if not restricted though some design patterns or lack of memory).

Now, lets come to Static and Non-static Synchronized method calls -

Static Synchronized Method Call - Whenever a thread accesses any synchronized static method, it acquires the lock on Class object of that class and hence no other static method can be accessed of that class.

Non-static Synchronized Method Call - As the non-static methods can be accessed through only objects of that class. So whenever, a thread enters any non-static synchronized method, it acquires the lock on the object through which the call has been made. Hence the other threads can still access the same or other non-static methods using other unlocked objects (free resources) of that class.

ShareThis