Tuesday, November 24, 2015

Singleton Class


Singleton class is that for which, we can create only one or single instance of the class through the life cycle of program. In other words, we are restricting user to create multiple instance.

For example, we don’t want to create connection object if it is already created. We should make our connection class as singleton class.

Below is code snippet, how to make singleton class.





/*Singleton Class*/
class TryCatch {

       private static TryCatch singleton = new TryCatch();

       /*Constructor is private because we don’t want to create object outside of the class*/
       private TryCatch() {

              System.out.println("In private constructor…");
       }

       /* Static 'instance' method */
       public static TryCatch getInstance() {
              return singleton;
       }
}



/*Main Class*/
public class TryCatchMain {

       public static void main(String[] args) {
             
             
              TryCatch object = TryCatch.getInstance();

       }

}


Sunday, November 15, 2015

New and Best Features of Java 8


Get a new tool set for easily performing common operations.

I've been giving a presentation called "Java 8 in Anger." No, it's not that the most recent release of Java has me particularly enraged; in anger is (apparently) a British phrase meaning "in practice" or "in the real world."



The aim of the talk is to demo, with live code, how to use some of the Java SE 8 features such as lambda expressions and the Stream API to solve some of the coding problems you might come across in your day job as a developer.

For more details click on Feature of Java 8.


Friday, November 13, 2015

What is Thread


Thread is a flow of execution and a program in itself. Each thread has its own job to perform. We can create a thread by using two things:

1)  Extending Thread class &
2)  Implementing Runnable interface.





Here is one more class i.e. ThreadGroup. This class is use to group number of threads as per their behavior. This class is helpful, if we want to change behavior of multiple threads of same group at once.

Thread class has multiple methods to implement required job. But, in case of Runnable interface, it has only run() method.

We should implement runnable interface because by extending thread class we will never extends other classes if required.



Each thread has some property, which are

1)  Name: By setting name, we can identify the thread by its name. By default name is Thread0, Thread1…

2)  Priority: By setting name, we can set the execution chance priority. We can set from 1 to 10. By default priority is normal i.e. 5.

3)  Group: We cannot set group of threads. It is automatically set by JVM. We can only get group name of thread.


Thread class implements Runnable interface.


Wednesday, November 4, 2015

Thread States






1)      New/Born:  When we create object of thread class, it is in new or born state.

2)      Runnable/Ready: After creating object, when we call start() method of thread class, it comes into runnable or ready state.

3)      Running: When thread scheduler will assign or allocate processor while calling run() method to thread then it comes into running state.

4)      Dead: After completion of job assigned to thread, when we call stop() method then it comes to dead state.

5)      Yield: It means, we want back to Runnable/Ready state. For this, we need to call static method of Thread class yield().

6)      Blocked: When we call join() method, that’s mean we want to block till the joined thread will complete its job or till the time not get finished or not get interrupted.

7)      Sleep: When we call sleep() method, thread will exists into sleeping state.

8)      Waiting: While calling wait() method, thread comes into waiting state. It will come to ready state only if we call notify() or notifyAll() method.


9)      Suspended: While calling suspend() method, thread comes into suspend state. It will come to ready state only if we call resume() method


Transient Keyword


To understand transient keyword, we must know the concept of serialization. In serialization, Java object represented as a sequence of bytes with data and its type. Object has been written into a file.

Now to declare any object serialized, we must implement Serializable interface and declare the object as transient. Any of the transient variables never is serialized. In the below example, we declare String middleName as transient.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class TryCatchData implements Serializable {
       private String firstName;
       private transient String middleName;
       private String lastName;

       public TryCatchData(String firstName, String middleName, String lastName) {
              this.firstName = firstName;
              this.middleName = middleName;
              this.lastName = lastName;
       }

       public String toString() {
              StringBuilder builder = new StringBuilder();
              builder.append("First Name : ");
              builder.append(this.firstName);
              builder.append(" Middle Name : ");
              builder.append(this.middleName);
              builder.append(" Last Name : ");
              builder.append(this.lastName);
              return builder.toString();
       }
}



public class TryCatch {
       public static void main(String args[]) throws Exception {
              TryCatchData writeData = new TryCatchData("Try", "2", "Catch");
              ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream("TryCatchData"));
              outStream.writeObject(writeData);
              outStream.close();

              ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("TryCatchData"));
              TryCatchData readData = (TryCatchData) inputStream.readObject();
              System.out.println(readData);
       }
}

Output: First Name : Try Middle Name : null Last Name : Catch


Tuesday, November 3, 2015

Volatile Keyword

Volatile is a modifier keyword. Volatile can be use with only variables not with class or method names. When a variable declared as volatile it means, the value of the variable should be taken from main memory of its stack not from cached thread-locally. A variable value will be modified by different threads. This keyword has to declare in synchronized block.



public class TryCatch {

       private static volatile int volatileVariable = 0;

       public static void main(String[] args) {
              new Listener().start();
              new Maker().start();
       }

       static class Listener extends Thread {
              @Override
              public void run() {
                     int LocalVariable = volatileVariable;
                     while (LocalVariable < 5) {
                           if (LocalVariable != volatileVariable) {
                                  System.out.println("Got Change for volatileVariable : " + volatileVariable);
                                  LocalVariable = volatileVariable;
                           }
                     }
              }
       }



       static class Maker extends Thread {
              @Override
              public void run() {

                    int localVariable = volatileVariable;
                     while (volatileVariable < 5) {
                           System.out.println("Incrementing volatileVariable to " + (localVariable + 1));
                           volatileVariable = ++localVariable;
                           try {
                                  Thread.sleep(1000);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                     }
              }
       }

}


Friday, October 23, 2015

Synchronized Keyword


Synchronized is a keyword use for thread concepts. There are chances when two or more threads are trying to access same resource. At this point, program will get stuck or hang. So to come over this situation java has synchronized keyword.
We just need to share those resources to synchronized block.



public class TryCatch {
       public static void main(String args[]) {

              CounterDemo counterDemo = new CounterDemo();

              ThreadDemo thread1 = new ThreadDemo("Thread - 1 ", counterDemo);
              ThreadDemo thread2 = new ThreadDemo("Thread - 2 ", counterDemo);

              thread1.start();
              thread2.start();

              try {
                     thread1.join();
                     thread2.join();
              } catch (Exception e) {
                     System.out.println("Interrupted");
              }
       }
}

class CounterDemo {
       public void counterCount() {
              try {
                     for (int i = 0; i <= 10; i++) {
                           System.out.println("Counter   ---   " + i);
                     }
              } catch (Exception e) {
                     System.out.println("Thread  interrupted.");
              }
       }

}

class ThreadDemo extends Thread {
       private Thread thread;
       private String threadName;
       CounterDemo counterDemo;

       ThreadDemo(String name, CounterDemo counterDemo) {
              threadName = name;
              this.counterDemo = counterDemo;
       }

       public void run() {

              /*
               * Try to run this code with uncomment and comment line 53. You will see
               * the difference
               */
             
              // counterDemo.counterCount();

              synchronized (counterDemo) {
                     counterDemo.counterCount();
              }

              System.out.println("Thread " + threadName + " running...");
       }

       public void start() {
              System.out.println("Starting " + threadName);
              if (thread == null) {
                     thread = new Thread(this, threadName);
                     thread.start();
              }
       }


}