Sunday, June 25, 2017

Creating Thread using Extending Thread Class

Here is an example of creating thread using extending Thread class mechanism. Moreover, example also help you to understand, how to pass the values to thread and use different methods like Sleep, interrupt etc.


Creating Thread using Implementing Runnable Interface

Here is an example for creating thread and passing values to it.
There are two ways to create thread in java
1) Implementing Runnable Interface
2) Extending Thread Class
This example uses first option

Finding object in List ( Use of Contain)

Here is an example of searching object in List. Trying to list down all possible ways of finding object from List.
1) Searching String from list.
2) Searching Employee Object using contain method
2) Using Stream API (Java 8)





Wednesday, June 21, 2017

Immutable Class in java

Here is the example, how to create immutable Class in java

package com.nitesh;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
 * Make all fields final and private.
 * Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is 
 * to make the constructor private and construct instances in factory methods.
 * If the instance fields include references to mutable objects, don't allow those objects to be changed:
 * Don't provide methods that modify the mutable objects.
 * Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, 
 * and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
 * @author Nitesh.Gupta
 *
 */
public final class MyImmuatable {
/**
* Final Integer field, Integer is anyways immutable
*/
private final Integer immutableField1;
/**
* Final String field
*/
private final String immutableField2;
/**
* Final Date object which is mutable and need to be taken care explicitly
*/
private final Date immutableField3;
/**
* Final List Object which is mutable 
*/
private final List immutableField4;
/**
* Constructor which is taking all inputs through parameters
* @param immutableField1
* @param immutableField2
* @param immutableField3
* @param immutableField4
*/
public  MyImmuatable (Integer immutableField1, String immutableField2, Date immutableField3,List immutableField4){
this.immutableField1 = immutableField1;
this.immutableField2 = immutableField2;
this.immutableField3 = new Date(immutableField3.getTime());
this.immutableField4 = Collections.unmodifiableList(immutableField4);
}

public Integer getImmutableField1() {
return immutableField1;
}

public String getImmutableField2() {
return immutableField2;
}

public Date getImmutableField3() {
return immutableField3;
}

public List getImmutableField4() {
return immutableField4;
}

@Override
public String toString() {
return "MyImmuatable [immutableField1=" + immutableField1 + ", immutableField2=" + immutableField2
+ ", immutableField3=" + immutableField3 + ", immutableField4=" + immutableField4 + "]";
}


}

Monday, June 19, 2017

Singleton Class in Java

Here is the example of complete singleton class which implements Cloenable and Serializable as well.

Read inline java comments for more details

package com.nitesh;

import java.io.Serializable;
/**
 * This class returns singleton Object and tries to handle all possible cases to avoid
 * creating multiple instance of MySingleton Class
 * Following given steps 
 * 1) Created INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
 * 2) Provide public static method that returns same INSTANCE of class every time
 * 3) Create private constructor so that no-one create object from outside of class
 * 4) Providing private constructor helps to suppress creating objects either by new operator/keyword or refection API & newInstance() method
 * 5) Implementing Serializable interface, and override readResolve() method and return same INSTANCE
 * 6) Implementing Cloneable interface and overridden clone() method and throw CloneNotSupportedException();
 *  @author Nitesh.Gupta
 *
 */
public class MySingleton implements Cloneable, Serializable {

private static final long serialVersionUID = 1L;
/**
* Creating a INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
* and with EAGER Loading (creating object using new operator)
*/
private static MySingleton instance = new MySingleton();
/**
* Private constructor to avoid creating instance from outside class.
* Moreover, checking object reference if someone tries to create object using reflection.
*/
private MySingleton() {
if (instance == null) {
throw new IllegalStateException();
}
}
/**
* Static method for returning single object of MySingleton Object 
* @return Object of MySingleton
*/
public static MySingleton getInstance() {
return instance;
}
/**
* ReadResolve method to avoid creating new instance in case of De-serialization 
* @return same object
*/
public Object readResolve() {
return getInstance();
}
/**
* Overriding clone method throwing CloneNotSupportedException exception if 
* someone tries to clone this class
*/
@Override
protected Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}
}

Java Thread Example

In this example, Five Threads are being invoked which takes input as Integer and prepare table. Also, Used some of methods like Sleep and isInterrupted to understand its uses.

package test;
/**
 * MyThread2 class which creates thread by extending Thread Class
 * @author Nitesh.Gupta
 */
public class MyThread2 extends Thread {
/**
* Initializing count with 1
*/
private int count=1;
/**
* MyThread constructor which takes an input and assign it to class level variable
* @param count
*/
MyThread2 (int count){
this.count = count;
}
/**
* Run method which gets executed as soon as thread.run called.
*/
@Override
public void run() {
calculateTable();
}
/**
* Helper method for calucalting table
*/
private void calculateTable() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
for (int i=1; i<=10 ; i++){
int counting = i * count;
System.out.println("Table of " + i + " Prepared by Thread "+this.getId() +" Name "+this.getName());
System.out.println("Count of " + count + "*" + i + "=" +counting);
}
}
public static void main (String str[]) throws InterruptedException{
for (int k=1; k<5 font="" k="">
Thread.sleep(1000);
MyThread2 t1 = new MyThread2(k);
t1.start();
//IsInterrupted method to check if thread is interrupted in between or not
if (t1.isInterrupted()){
throw new InterruptedException();
}
}
}
}