Month: April 2016

Difference between List, List<E>, List<Object>, and List<?> in java

Posted on

java-logoThis is very important topics in Generic to know the difference between List, List<?>,  List<E>, and List<Object>. Enabling Generic in you application code provides you a flexibility of code to work on different type of Data type and ensure to Type safety and easy to read.

In this example, we took a Collection Type i.e List but it can be any Collection Type i.e Set, LinkedList  and Map.

 

List

It’s a raw type and not type safe. It will generate a Runtime exception when casting is bad.


                List list = new ArrayList();
		list.add("Hello");
		list.add(234);
		list.add(new Object());
		// explicitly cast require here
		String s = (String) list.get(0);

 

List<E>

It’s a parameterized type and ‘E‘ can be referred to any non-primitive type, any class type, any interface type, any array type, or even another type variable.


public <E> List<E> unmodifiableList(List<E> list) {
  Collections.unmodifiableList(list);
  return list;
 }

E i.e element can be replaced with some concrete type like String,Integer,Number and other class, interface type.

List<Object>

It is a parameterized type of Object and It’s only allowed to add Object sub-type But does not allow to assign the sub-type reference into that list- means List<Object> instance will not accept the references of List<String> because List<String> is not a subtype of List<Object>, therefore compile generate a compiler errors.


List<Object> listOfObject = new ArrayList<Object>();
listOfObject.add("Hello");
listOfObject.add(234);
// OK
Object o = listOfObject.get(0);

List<String> listOfString = new ArrayList<String>();
listOfString.add("Hi");
//Error :- Type mismatch: cannot convert from List<String> to List<Object>
listOfObject = listOfString; // Compiler time error - Bad casting
List<Object> list1 = listOfString; // Compiler time error - Bad casting

List<Object> list2 = list1; // OK

List<?>

‘?’ Question marks represented an unknown type. List<?> can be something that we don’t know right now. It’s also considered as READ-ONLY list where no any write operation will be performed only read operation is allowed like iteration over it, sizes of list and etc.

List<?> listOnUnknow = new ArrayList();
listOnUnknow.addAll("hello"); // Error because compiler don't know what type of value is going to store here.

We can do it like this :-


public static void reverse(List<?> list) {
     int size = list.size();
     if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
           swap(list, i, j);
     } else {
    ListIterator fwd = list.listIterator();
    ListIterator rev = list.listIterator(size);
    for (int i=0, mid=list.size()>>1; i<mid; i++) {
    Object tmp = fwd.next();
    fwd.set(rev.previous());
    rev.set(tmp);
}
}
}

Thanks

Difference between JVM, JDK,JRE and JIT

Posted on

java-logo

These are the core concept of Java programming language. Most of Java developer are always confused to link between these concepts. Although these looks similar but they are different from each other and their specification.
However, a JVM comes along with JRE & JDK libraries but JRE,JDK and JVM are dependent on operating system machine but Java is independent. here we will see the difference between these and usages :-

Java Virtual Machine (JVM)

JVM is  an abstract machine and subsystem of JDK & JRE. A java program execution uses a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that is, virtual and doesn’t really exist. This so-called “virtual” computer is known as the Java virtual machine (JVM). The machine language for the Java virtual machine is called Java bytecode.
Java Virtual Machine is a program that runs pre-compiled Java programs, which mean JVM executes .class files (byte code) and produces output. The JVM is written for each platform supported by Java included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language. There are many JVM implementations developed by different organizations i.e IBM

The JVM performs following main tasks:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

 

main-qimg-fa65b143171397549e5169a2f7167cc5

 

Java Development Kit (JDK)

JDK stands Java Development Kit, it includes the JRE, set of API classes, Java compiler, Webstart and additional files needed to write Java applets and applications.  So final conclusion is it content every file which useful in developing an application whether it standalone or web based.

Java Development Kit is a bundle of the following software components that are needed to develop Java based applications.

main-qimg-3d375760a6564a7b34c5936dfd66a814

Java Runtime Environment (JRE)

JRE provides Java Runtime environment to run an applet and Java-related web applications. It is an implementation of the JVM which actually executes Java programs. It includes the JVM, core libraries and other additional components to run applications and applets written in Java. Java Runtime Environment is a must install on a machine in order to execute pre-compiled Java Programs. JRE is smaller than the JDK so it needs less disk space and it is so because JRE does not contain Java compiler and other software tools needed to develop Java programs.

Just in Time Compiler (JIT)

JIT are advanced part of Java Virtual machine (JVM) which is used to optimize byte-codes to machine instruction conversion part by compiling similar byte-codes at the same time and thus reducing overall execution time. JIT is part of Java Virtual Machine and also performs several other optimizations such as inline function.

 

Difference between Association,Aggregation,Composition and Inheritance

Posted on

Most of you are familar with these terms are being used when we design a object-oriented model diagram. These relationship not only represents static view of your application but also representing construction of executable code of software application.

It’s adding more advantage of developing a software appliaction by designing the relationship between classes, their responsibility and implementation which helps to construct the executable code for forward and reverse engineering of any system.

uml_symbols

Association:-

Association is a relationship between two objects. It’s denoted by “has-a” relationship. In this relationship all objects have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation:-

Aggregation is a another type of specialised form of Association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not be destroyed. We can think about it as a “has-a” relationship.

Composition:-

Composition is again specialised form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have its lifecycle and if parent object is deleted, all child objects will also be deleted. Let’s take again an example of relationship between House and Rooms. House can contain multiple rooms – there is no independent life of room and any room can not belong to two different houses. If we delete the house – room will automatically be deleted. Let’s take another example relationship between Questions and Options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically be deleted. Let’s take another example of relationship between Car and Moter, Moter is a vital part of Car, if you remove moter then Car become useless.

Hence, we can take lots of example of composition in real world that represent a strong relationship classes .

Inheritance :-

Inheritance is an another type of relationship and it’s denoted by “is-a” relationship. Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a base class in a derived. for example- Circle is a shape, Rectangle is a Shape.

 

Java 8 – Default Methods

Posted on

Java-8

In my previous posts, we have discussed on Lambda Expressions in Java 8.  In this post we will discuss other cool features of Java 8 is Default methods.

Default methods enable you to add new functionality to the interfaces without breaking the class that implements that interface. It ensures that compatibility with code written for older versions of those interfaces.

A Default method is denoted by a keyword “default” by adding it before function access modifier. Also, an Interface or Functional Interface  can have one or more default methods.

default void method1(){

           // Default method body …..

}

According to “Open and Close” principle, which is also intended to open for extension but closed for modifications is stated that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Prior to Java 8, An interface can contain only abstracts methods and all classes that implement that Interface must be implemented all abstracts methods by the rule if any new functionalities need to be added into existing Interface that all implementor classes should be forced to implement the Interface’s methods. More likely it’s incompatible with code written for older versions of Interface then more efforts need to be required to change across the implementor classes.

By approaching default methods in Java 8, it can be fixed this issue by introducing the default methods in Interface. Default  methods do not force to override in subclasses, It is up to you either you can override or not.

Look at the below snippet code of Default Methods in Java 8.

Default method provides us a fixability to allow a method to be implemented in Interface. so Implementation may be used as default method  if a concrete class does not provide the implementation for that.


interface Calculable {
                // abstract method 
		int calc(int x, int y);
		// default method
		default void method(){
			System.out.println("hello");
		}
	}

In this snippet code example, calc() is an abstract method and method() is a default method which has been given the body. However, in this case,  Calculable is a Functional Interface.

Default methods in Multiple Inheritance :-

Since in Java, We can implement  multiple  inheritance  by using Interface but what happened if two or more Interfaces have  a default method with the  same signature then it’s causing a conflict in methods calls in implementor classes. Look at the below code, We have created two Interface i.e Executor & Runnable that have two methods respectively one is an abstract method and other is a default method that is exactly same as both Interface.

Here, MyClass is implemented both Interface Runnable & Executor then subsequently compiler reported a Compile time error i.e

“Duplicate default methods named getStatus with the parameters () and () are inherited from the types Runnable and Executor.”


package com.excerise1;

interface Executor {

	void execute();

	default void getStatus() {
		System.out.println("Ready to Execute.");
	}

}

interface Runnable {
	void run();

	default void getStatus() {
		System.out.println("Ready to Run.");
	}
}
/*
  COMPILER Errors:- Duplicate default methods named getStatus with the parameters () and () are inherited 
                    from the types Runnable and Executor
 */
public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}
}


In above code, Compiler force to override either one of default methods of Runnable or Executor Interface, Otherwise Compiler will not know what default method to used at a time.

In order to workaround solution, we implement default method in subclass i.e MyClass therefore it’s overriding both methods of Runnable & Executor Interface.


public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getStatus() {
		
	}
}


In the above code, getStatus() methods has a dummpy body or own definitation but if you want to invoke one of either Runnable or Executor default methods then we do it as following ways:-


        @Override
	public void getStatus() {
		Runnable.super.getStatus();
	}
   // OR
	/*@Override
	public void getStatus() {
		Executor.super.getStatus();
	}*/

Thanks
——-

Java 8 – Lambda Expressions

Posted on Updated on

Java-8

What is Lambda Expressions in Java 8 ?

First, it was introduced in Java 8, which is one of most powerful features of Java 8.

Lambda is a functional programming which is a way to passing a block of code to function argument.  JavaScript is one of  the best example of functional programming. A functional programming has evolved to avoid the changing state and mutable data. It is a declarative programming that is done on expression and declarative rather than statements.

Syntax of Lambda Expression:- 

(parameters)-> expression body

  • Lambda expression can have zero,one or more parameters.
  • Type of Lambda parameter can have explicitly declared or depend on the context.
    • ()->System.out.println(“hello how are u”);
    • (username)->System.out.println(“Welcome, “+username+” This is test message”);
    • (x,y)->return (x+y);
    • (int x,inty)->return (x+y);
  • Body of Lambda Expression can contain zero,one and multi line statements.
  • Multi line expression body can be enclosed by curly brackets.

()->{
System.out.println("Hello, This is first statement");
System.out.println("Hello, This is Second statement");
}

Example Of Lambda Expression :-


package com.excerise1;

public class Java8LambdaTest {

	public static void main(String args[]) {

		new Thread(() -> {
			System.out.println(" This is Thread " + Thread.currentThread().getName());
		}).start();

		Runnable runnable = () -> {
			for (int i = 0; i < 5; i++) {
				try {
					System.out.println(
							" This is Thread " + Thread.currentThread().getName() + " with Iteration (" + i + ")");
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}
}

In the above code, Compiler can automically cast Lambda Expression to Runnable so no any casting required.

Output here :-

This is Thread Thread-0
This is Thread Thread-1 with Iteration (0)
This is Thread Thread-1 with Iteration (1)
This is Thread Thread-1 with Iteration (2)
This is Thread Thread-1 with Iteration (3)
This is Thread Thread-1 with Iteration (4)

 

What is Functional Interface?

A functional interface is a interface that has only one abstract method on it. like Runnable interface that has only one methods i.e run(). Each Lambda Expression can be implicitly assigned a interface called Functional Interface.

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

@FunctionalInterface annotation is used to indicate that a Interface type declaration is intended to be a Functional Interface. It can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface.

i.e in the below code, Compiler generated an compile time errors-
Invalid ‘@FunctionalInterface’ annotation; Executable is not a functional interface


@FunctionalInterface
interface Executable{
	void execute();
	void submit();
}

Example of Funcational Programming:-


package com.excerise1;

import com.excerise1.Calculator.Calculable;

class Calculator {
	interface Calculable {
		int calc(int x, int y);
	}

	interface Addition extends Calculable {
	}

	interface Substraction extends Calculable {
	}

	interface Multiply extends Calculable {
	}

	interface Divide extends Calculable {
	}

	private int number1;
	private int number2;

	public Calculator(int x, int y) {
		this.number1 = x;
		this.number2 = y;
	}

	public int calc(Calculable cal) {
		return cal.calc(number1, number2);
	}

}

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

		Calculable addition = (a, b) -> (a + b);
		Calculable substraction = (a, b) -> (a < b ? b - a : a - b);
                Calculable multiply = (a, b) -> (a * b);
		Calculable divide = (a, b) -> (a / b);

		Calculator cal = new Calculator(10, 20);
		System.out.println(" Addition Result is :" + cal.calc(addition));
		System.out.println(" Substraction Result is :" + cal.calc(substraction));
		System.out.println(" Multiply Result is :" + cal.calc(multiply));
		System.out.println(" Dividision Result is :" + cal.calc(divide));

	}
}

Output here :-

 Addition Result is :30
Substraction Result is :10
Multiply Result is :200
Dividision Result is :0

Here, Lambda Expression is matched against the parameter of calc() method parameters, if Lambda Expression matches with the parameters of calc() then Lambda expression can turn into a function that implements the same interface as that parameter.

Deadlock in Java

Posted on Updated on

product-development-using-javaThis is the one of the favorite questions in multithreading interview at senior level experience and it also most frequently asked question in Java interview. Most of Java experience developer get confused while answering the correct and appropriate answer as well as the cross questing.

Interviewer also expects to know about actual scenario and how to handle deadlock situations in multi-tasking application. It might be asked some real scenario when you have ever or recently encountered with such situations and what appropriate action has been taken to come over ?

So, in this post, I would demonstrate how an application encounters with deadlock situation and how to prevent it.

What is a Deadlock in Java ?

Deadlock is a situation in multi-tasking application when two or more threads  are waiting for each other to release the monitor lock and get stuck forever.
deadlock

Deadlock example here:-


package com.threading.example;

class DeadLock {
	public void method1() {
		synchronized (Number.class) {
			System.out.println("Obtained a lock on Number.class Object by Thread" + Thread.currentThread());
			synchronized (Integer.class) {
				System.out.println(" Obtained a lock on Integer.class Object by Thread" + Thread.currentThread());
			}
		}
	}

	public void method2() {
		synchronized (Integer.class) {
			System.out.println("Obtained a lock on Integer.class Object by Thread" + Thread.currentThread());
			synchronized (Number.class) {
				System.out.println(" Obtained a lock on Number.class Object by Thread" + Thread.currentThread());
			}
		}
	}
}

class MyThread1 implements Runnable {
	private DeadLock deadLock;

	public MyThread1(DeadLock deadLock) {
		this.deadLock = deadLock;
	}

	public void run() {
		deadLock.method1();
	}

}

class MyThread2 implements Runnable {
	private DeadLock deadLock;

	public MyThread2(DeadLock deadLock) {
		this.deadLock = deadLock;
	}

	public void run() {
		deadLock.method2();
	}

}

public class DeadLockTest {
	public static void main(String args[]) {
		DeadLock deadLock = new DeadLock();
		//waiting to lock on java.lang.Integer object
		Thread t1 = new Thread(new MyThread1(deadLock), "Thread 1");
		//waiting to lock on java.lang.Number object
		Thread t2 = new Thread(new MyThread2(deadLock), "Thread 2");
		t1.start();
		t2.start();
	}
}

In the above code, method1() and method2() can be called by more than on Threads. When t1 thread call method1() then t1 acquired a monitor lock on Number.class Object and at same time t2 thread also call method2() subsequently acquired a monitor lock on Integer.class Object. Both threads are waiting for each other here to release the lock to proceed the further which will never happen.

If you see the above code carefully then nested synchronized blocks are used in method1() & method2() and each synchronized block try to acquired two different lock on different order in method1() and method2() that subsequently chance to occured deadlock.

How do you find out that your application has encountered with Deadlock situation ?

One way to trace out the deadlock situation is using JConsole or jvisualvm ( Java Visual VM ) that found under /bin folder in your JAVA_HOME directory.

-Step’s to reproduce the deadlock situation:-

  • Run above code in your machine.
  • When you run this program then program will never be terminated due to deadlock situation.
  • go to /bin folder under JAVA_HOME and run jvisualvm.exe at your machine.
  • When jvisualvm will be lunched then it shows all Java process running on the machine.
  • double click on DeadLockTest java process then at right side panel all JVM information will be displayed i.e Heap,PremGen,CPU information etc.
  • Click on Thread tab that would display all live threads information and then click on “Thread Dump” button that will be displayed JVM dump information.
  • In JVM dump information, you can easily figure out exactly where the deadlock situation occurred.
  • Once you able to figure out where the actual problem exists then issues could be fixed.

deadlock-thread-info

deadlock-thread-dump-info

How to avoid Deadlock situation ?

If you see the above code carefully then you may have figured out the real solution of deadlock is order they are requesting for locks is different than requesting for locks on different methods. If these two methods are called by two or more thread then there are no way to release the lock. Each thread get stuck and waiting for releasing the locks which has been already to held by another thread.

Here, another version of Deadlock class that prevent to deadlock situation in java. In this example we maintained order of nested synchronized block on different object locks must be same as another synchronized block. if a thread acquired a lock on Number.class object while executing a method1() or method2() then another thread will wait until Number.class object lock get released and vice-visa.


class DeadLock {
	public void method1() {
		synchronized (Number.class) {
			System.out.println("Obtained a lock on Number.class Object by Thread" + Thread.currentThread());
			synchronized (Integer.class) {
				System.out.println(" Obtained a lock on Integer.class Object by Thread" + Thread.currentThread());
			}
		}
	}

	public void method2() {
		synchronized (Number.class) {
			System.out.println("Obtained a lock on Number.class Object by Thread" + Thread.currentThread());
			synchronized (Integer.class) {
				System.out.println(" Obtained a lock on Integer.class Object by Thread" + Thread.currentThread());
			}
		}
	}
}