Tuesday 26 August 2014

Difference between Callable and Runnable in java

The first thing both Callable and Runnable are interface. Runnable might be heard a lot because it is used to create Thread. But Callable is added on java5 where as Runnable is present from jdk1.0.

Let's try to understand both -
Runnable- It is a interface and present from jdk1.0.It has run() method where we can execute task. method signature is given below-

public void run()
{
//task
}
here method return type is void
 
When we execute sometask in different thread then we can use Runnable interface but the thread can not return any result in this case because the return type is void.  And this execute by Thread. e.g.

class MyRunnable implements Runnable{
 public void run(){
  System.out.print("runabletask")
 }
 
public static void main (String args[]){

  Thread t= new Thread(new MyRunnable());
  t.start();
 
  //or start runnable by executor
  //ExecutorService executor =  Executors.newFixedThreadPool(2);
  //executor.execute(new MyRunnable());
 }
} 

Callable - It is also a interface which is present from jdk5.0.It has call() method. It is used for parallel execution hence it is part of concurrent api, present in java.util.concurrent package.
Method signature is given below

public V call()throws Exception
{
//task
}
 
here method return type is Generic type V That means, can be passed from parameter of class  This return called future object of java.util.concurrent.Future package. As run method doesn't return any result so, in jdk5.0 introduced Callable.In some situation when we want return some result after thread execution finish then we can use Callable interface.This also execute by Thread. e.g.

class MyCallable implements Callable<String>{ 
 
 public String call()throws Exception{
  System.out.print("callable task")
 }

public static void main(String...args){ 
 ExecutorService executor =  Executors.newFixedThreadPool(2);
 
 List<Future<String>> list = new ArrayList<Future<String>>();
 
 MyCallable  callable = new MyCallable();
 for(int i=0; i< 100; i++){
  Future <String>future = executor.submit(callable);
  list.add(future);
 }
 for(Future <String>future:list){
  try {
    System.out.println(future.get());
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
  executer.shutdown(); 
 } 

To create Thread pool in java Executer class used and These Thread pool will 
hold Thread to execute Callable or Runnable in a thread pool.Since callable or Runnable tasks run in parallel, we have to wait for the returned 
Object in case of Callable. Callable tasks return java.util.concurrent.Future object. 
Using Future we can find out the status of the Callable task and get the 
returned Object. It provides get() method that can wait for the Callable to 
finish and then return the result.

Future also provides cancel() method to cancel the Callable task. There is an overloaded version of get() method
 where we can specify the time to wait for the result, it’s useful to 
avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.



 

Wednesday 20 August 2014

What is difference among String, StringBuffer and StringBuilder?

The difference among String, StringBuffer and StringBuilder-

Monday 11 August 2014

How to create Immutable Object and class in java

How to create Immutable Object and class in Java this is most commonly question asked by interviewer.
Before going to explain how to create Immutable, let's understand what is means of Immutable.
Immutable means not changeable, once created.e.g There is a multiple scenario when we need object or class that look like final variable. final variable is variable that can not be reassigned again.
The main use case of Immutable is-
  1. Object can be shared in threaded environment, because no thread can modify the object. Hence in this case synchronization block is also not required and if program does not has synchronization block then performance will be more.
  2.  Suppose you are using object as a key in HashMap or Hashtable then making immutable key means always value can be accessible by key. assume if key is not immutable then after set value in hashmap or hashtable if any body change the key from outside then accessing the value by key is tough.
  3. Caching is other use case. if you cache immutable object then any time can be accessible without any modification.
 Here in this topic immutable means can not modified/changed/updated/reassigned, once created.

Now the question is how to create immutable object and class?
It's very easy just follow some basic points during the creating class, which are-
  1. Don't provide setter methods this will prevent the fields value to be modify from outside or inside of the class.
  2. All the fields of class should be final. This will prevent the fields to be reassigned again.
  3. All the fields of class should be private.This will prevent the fields to be access from outside or from reflection api.
  4. Create the final class. This will prevent the class from subclassing. e.g class can not be overridden.
  5. Make sure no such methods is present in the class that is updating the state/fields.
  6. Declare the constructor of the class as private and add a factory method to create an instance of the class when required.
For example-
    each person has unique mobile number so below immutable class is created to store mobile number for person class-

                   final class ImmutablePersonClass{
                          private static ImmutablePersonClass instance = new ImmutablePersonClass();
                          private long final mobileNumber;
                        
                          private ImmutablePersonClass(long mobileNumber){
                             this.mobileNumber= mobileNumber;
                         }
                       
                          public long getMobileNumber(){
                            return mobileNumber;
                          }
                         
                          public ImmutablePersonClass getImmutablePersonClass(){
                           return instance;    
                          }

                     }

Wednesday 6 August 2014

Java - Thread Synchronization, Locking, Priority, Thread Scheduler, Wait And Notify, Joining, Deadlock

Thread Synchronization in JAVA
Threads share the same memory space, that is, they can share resources. However, 
there are critical situations where it is desirable that only one thread at a time has 
access to a shared resource. For example, crediting and debiting a shared bank 
account concurrently amongst several users without proper discipline, will 
jeopardize the integrity of the account data. Java provides high-level concepts for 
synchronization in order to control access to shared resources.

A lock is used to synchronize access to a shared resource. A lock can be associated 
with a shared resource. Threads gain access to a shared resource by first acquiring 
the lock associated with the resource. At any given time, at the most one thread can
hold the lock (i.e., own the monitor) and thereby have access to the shared resource.
A lock thus implements mutual exclusion.
In Java, all objects have a lock—including arrays. This means that the lock from any 
Java object can be used to implement mutual exclusion. By associating a shared 
resource with a Java object and its lock, the object can act as a guard, ensuring 
synchronized access to the resource. Only one thread at a time can access the 
shared resource guarded by the object lock.
The object lock mechanism enforces the following rules of synchronization:
A thread must acquire the object lock associated with a shared resource, before it 
can enter the shared resource. The runtime system ensures that no other thread 
can enter a shared resource if another thread already holds the object lock 
associated with the shared resource. If a thread cannot immediately acquire the 
object lock, it is blocked, that is, it must wait for the lock to become available.
When a thread exits a shared resource, the runtime system ensures that the object
lock is also relinquished. If another thread is waiting for this object lock, it can 
proceed to acquire the lock in order to gain access to the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. 
Such a lock is actually a lock on the java.lang.Class object associated with
the class. Given a class A, the reference A.class denotes this unique Class 
object. The class lock can be used in much the same way as an object lock 
to implement mutual exclusion.The keyword synchronized and the lock form 
the basis for implementing synchronized execution of code. There are two 
ways in which execution of code can be synchronized:
  • synchronized methods
  • synchronized blocks

Synchronized Methods 
If the methods of an object should only be executed by one thread at a time, then 
the declaration of all such methods should be specified with the keyword synchronized.
A thread wishing to execute a synchronized method must first obtain the object's
lock,before it can enter the object to execute the method. This is simply achieved
by calling the method. If the lock is already held by another thread, the calling 
thread waits. No particular action on the part of the program is necessary. 
A thread relinquishes the lock simply by returning from the synchronized method, 
allowing the next thread waiting for this lock to proceed.
Synchronized methods are useful in situations where methods can manipulate the 
state of an object in ways that can corrupt the state if executed concurrently. A
stack implementation usually defines the two operations push and pop as 
synchronized, so that pushing and popping of elements are mutually exclusive
operations. If several threads were to share a stack, then one thread would, for 
example, not be able to push an element on the stack while another thread was 
popping the stack. The integrity of the stack is maintained in the face of several 
threads accessing the state of the same stack.
Synchronized Blocks
Whereas execution of synchronized methods of an object is synchronized on the 
lock of the object, the synchronized block allows execution of arbitrary code to 
be synchronized on the lock of an arbitrary object. The general form of the 
synchronized statement is as follows:

synchronized (<object reference expression>) { <code block> }

The <object reference expression> must evaluate to a non-null reference value, 
otherwise, a NullPointerException is thrown. The code block is usually related to 
the object on which the synchronization is being done. This is the case with 
synchronized methods, where the execution of the method is synchronized on the 
lock of the current object:
    
public Object pop() { 
  synchronized (this) {
     // Synchronized block on current object // ... 
     } 
}

Once a thread has entered the code block after acquiring the lock on the specified
object, no other thread will be able to execute the code block, or any other code 
aquiring the same object lock, until the lock is relinquished. This happens when 
the execution of the code block completes normally or an uncaught exception is 
thrown. In contrast to synchronized methods, this mechanism allows fine-grained 
synchronization of code on arbitrary objects.
Object specification in the synchronized statement is mandatory. A class can 



choose to synchronize the execution of a part of a method, by using the this 
reference and putting the relevant part of the method in the synchronized block. 
The braces of the block cannot be left out, even if the code block has just one statement.

           class SmartClient {
                     BankAccount account;
                     public void updateTransaction() {
                     synchronized (account) {
                     synchronized block account.update(); 
         }

    }
}

Synchronized blocks can also be specified on a class lock:

     synchronized (<class name>.class) { <code block> }

The block synchronizes on the lock of the object denoted by the reference 
<class name>.class. A static synchronized method classAction() in class A 
is equivalent to the following declaration:

      static void classAction() {
                 synchronized (A.class) {  }
      }
In summary, a thread can hold a lock on an object
  • by executing a synchronized instance method of the object
  • by executing the body of a synchronized block that synchronizes on the object
  • by executing a synchronized static method of a class
Thread Priorities
Every Java thread has a priority that helps the operating system determine the 
order in which threads are scheduled.Java thread priorities are in the range 
between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). 
By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be 
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and very much platform 
dependentant.

Thread Scheduler
Schedulers in JVM implementations usually employ one of the two following strategies:
Preemptive scheduling.If a thread with a higher priority than the current running
thread moves to the Ready-to-run state, then the current running thread can be 
preempted (moved to the Ready-to-run state) to let the higher priority thread execute.
Time-Sliced or Round-Robin scheduling.
A running thread is allowed to execute for a fixed length of time, after which it 
moves to the Ready-to-run state to await its turn to run again.
It should be pointed out that thread schedulers are implementation- and
platform-dependent; therefore, how threads will be scheduled is unpredictable, at 
least from platform to platform.

Waiting and Notifying
Waiting and notifying provide means of communication between threads that 
synchronize on the same object. 
The threads execute wait() and notify() (or notifyAll()) methods on the shared object 
for this purpose. These final methods are defined in the Object class, and therefore, 
inherited by all objects.These methods can only be executed on an object whose 
lock the thread holds, otherwise, the call will result in an IllegalMonitorStateException.

final void wait(long timeout) throws InterruptedException final void wait(long 
timeout, int nanos) throws InterruptedException 
final void wait() throws InterruptedException. A thread invokes the wait() method 
on the object whose lock it holds. The thread is added to the wait set of the object.

final void notify() final void notifyAll() A thread invokes a notification method on 
the object whose lock it holds to notify thread(s) that are in the wait set of the 
object. Communication between threads is facilitated by waiting and notifying,
A thread usually calls the wait() method on the object whose lock it holds because
a condition for its continued execution was not met. The thread leaves the Running 
state and transits to the Waiting-for-notification state. There it waits for this condition 
to occur. The thread relinquishes ownership of the object lock.
Transition to the Waiting-for-notification state and relinquishing the object lock 
are completed as one atomic (non-interruptable) operation. The releasing of the 
lock of the shared object by the thread allows other threads to run and execute 
synchronized code on the same object after acquiring its lock.
Note that the waiting thread does not relinquish any other object locks that it 
might hold, only that of the object on which the wait() method was invoked. 
Objects that have these other locks remain locked while the thread is waiting.
Each object has a wait set containing threads waiting for notification. Threads 
in the Waiting-for-notification state are grouped according to the object 
whose wait() method they invoked.A thread in the Waiting-for-notification state 
can be awakened by the occurrence of any one of these three incidents:

  • The waiting thread times out.
  • Another thread interrupts the waiting thread.
  • Another thread invokes the notify() method on the object of the waiting and the waiting thread is selected as the thread to be awakened.
Notify

Invoking the notify() method on an object wakes up a single thread that is waiting
on the lock of this object. The selection of a thread to awaken is dependent on the
thread policies implemented by the JVM. On being notified, a waiting thread first 
transits to the Blocked-for-lock-acquisition state to acquire the lock on the object, 
and not directly to the Ready-to-run state. The thread is also removed from the 
wait set of the object. Note that the object lock is not relinquished when the 
notifying thread invokes the notify() method. The notifying thread relinquishes the 
lock at its own discretion, and the awakened thread will not be able to run until 
the notifying thread relinquishes the object lock.
When the notified thread obtains the object lock, it is enabled for execution,
waiting in the Ready-to-run state for its turn to execute again. Finally, when it does
get to execute, the call to the wait() method returns and the thread can continue
with its execution.

A call to the notify() method has no consequences if there are no threads in the
wait set of the object.

In contrast to the notify() method, the notifyAll() method wakes up all threads in
the wait set of the shared object. They will all transit to the
Blocked-for-lock-acquisition state and contend for the object lock as explained
earlier.

Joining

A thread can invoke the overloaded method join() on another thread in order to
wait for the other thread to complete its execution before continuing, that is, the
first thread waits for the second thread to join it after completion. A running
thread t1 invokes the method join() on a thread t2. The join() call has no effect if
thread t2 has already completed. If thread t2 is still alive, then thread t1 transits
to the Blocked-for-join-completion state. Thread t1 waits in this state until one of
these events occur-
Thread t2 completes-In this case thread t1 is enabled and when it gets to run, it
will continue normally after the join() method call.
Thread t1 is timed out.-The time specified in the argument in the join() method
call has elapsed, without thread t2 completing. In this case as well, thread t1 is
enabled. When it gets to run, it will continue normally after the join() method call.
Thread t1 is interrupted-Some thread interrupted thread t1 while thread t1 was
waiting for join completion. Thread t1 is enabled, but when it gets to execute, it
will now throw an InterruptedException.

Deadlocks

A deadlock is a situation where a thread is waiting for an object lock that another
thread holds, and this second thread is waiting for an object lock that the first
thread holds. Since each thread is waiting for the other thread to relinquish a
lock, they both remain waiting forever in the Blocked-for-lock-acquisition state.
The threads are said to be deadlocked.

Thread t1 has a lock on object o1, but cannot acquire the lock on object o2.
Thread t2 has a lock on object o2, but cannot acquire the lock on object o1.
They can only proceed if one of them relinquishes a lock the other one wants,
which is never going to happen.

     public class DeadlockExample { 

           public static void main(String[] args) {
             final String resource1 = "ratan jaiswal";
             final String resource2 = "vimal jaiswal";
             // t1 tries to lock resource1 then resource2
             Thread t1 = new Thread() {
                 public void run() {
                   synchronized (resource1) {
                       
                        System.out.println("Thread 1: locked resource 1");

                           try { Thread.sleep(100);} catch (Exception e) {}

                            synchronized (resource2) {
                               System.out.println("Thread 1: locked resource 2");
                           }
                        }
                  }
           };

            // t2 tries to lock resource2 then resource1
           Thread t2 = new Thread() { 

              public void run() {
                synchronized (resource2) {
                   System.out.println("Thread 2: locked resource 2");
                   
                   try { Thread.sleep(100);} catch (Exception e) {}

                            synchronized (resource1) {
                               System.out.println("Thread 2: locked resource 1");
                           } 
                 }
            } ;
         t1.start();
         t2.start();
      }//end of main
   }// end of class

}

Thread In Java or Basics of Thread or Runnable vs Thread

Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:
  • Process-based multitasking
  • Thread-based multitasking 
Process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor. 

Thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word-processor that is printing and formatting text at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program concurrently. The sequence of code executed for each task defines a separate path of execution, and is called a thread (of execution).

In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted, for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.

Thread-based multitasking as compared to process-based multitasking are threads share the same address space context switching between threads is usually less expensive than between processes cost of communication between threads is relatively low. 

Java supports thread-based multitasking and provides high-level facilities for multithreaded programming. Thread safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.

Overview of Threads

A thread is an independent sequential path of execution within a program. e.g. It maintained in separate stack at runtime by JVM. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code, that is, they are lightweight compared to processes. They also share the process running the program.Every thread in Java is created and controlled by a unique object of the java.lang.Thread class. 

The Main Thread

When a application run, a user thread is automatically created to execute the main() method. This thread is called the main thread. If no other user threads are spawned, the program terminates when the main() method finishes executing. All other threads, called child threads, are spawned from the main thread, inheriting its user-thread status. The main() method can then finish, but the program will keep running until all the user threads have finished. Calling the setDaemon(boolean) method in the Thread class marks the status of the thread as either daemon or user, but this must be done before the thread is started. Any attempt to change the status after the thread has been started, throws an IllegalThreadStateException. Marking all spawned threads as daemon threads ensures that the application terminates when the main thread dies.

Thread Creation

A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:
  • By implementing the java.lang.Runnable interface
  • By extending the java.lang.Thread class
Implementing the Runnable Interface

The Runnable interface has the following specification, comprising one method prototype declaration:

                     public interface Runnable { void run(); }

A thread, which is created based on an object that should implement the Runnable interface, and should override it's public method run(). The run() method defines an independent path of execution and thereby the entry and the exits for the thread. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
An object of this class is a Runnable object.An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
The start() method is invoked on the Thread object to start the thread. The start() method returns immediately after a thread has been spawned.
The run() method of the Runnable object is eventually executed by the thread represented by the Thread object on which the start() method was invoked.




Example is given below-

public class CreateThreadRunnableExample implements Runnable{

       public void run(){
             
                for(int i=0; i < 5; i++){
                        System.out.println("Child Thread : " + i);
                     
                        try{
                                Thread.sleep(50);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
             
                System.out.println("Child thread finished!");
        }
     
        public static void main(String[] args) {
                Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");         
                t.start();
             
                for(int i=0; i < 5; i++){
                     
                        System.out.println("Main thread : " + i);
                     
                        try{
                                Thread.sleep(100);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
                System.out.println("Main thread finished!");
        }
}

output of this thread example would be

Main thread : 0
Child Thread : 0
Child Thread : 1
Main thread : 1
Main thread : 2
Child Thread : 2
Child Thread : 3
Main thread : 3
Main thread : 4
Child Thread : 4
Child thread finished!
Main thread finished!
Extending Thread Class-

A class can also extend the Thread class directly to create a thread.A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

 
The Thread class implements the Runnable interface, which means that this approach is not much different from implementing the Runnable interface directly. The only difference is that the roles of the Runnable object and the Thread object are combined in a single object.
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
public class CreateThreadExample extends Thread{
         public void run(){
             
                for(int i=0; i < 5; i++){
                        System.out.println("Child Thread : " + i);
                     
                        try{
                                Thread.sleep(50);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
             
                System.out.println("Child thread finished!");
        }
     
        public static void main(String[] args) {
              
                CreateThreadExample t = new CreateThreadExample();
                 t.start();
             
                for(int i=0; i < 5; i++){
                     
                        System.out.println("Main thread : " + i);
                     
                        try{
                                Thread.sleep(100);
                        }
                        catch(InterruptedException ie){
                                System.out.println("Child thread interrupted! " + ie);
                        }
                }
                System.out.println("Main thread finished!");
        }
}

 

Inner classes are useful for implementing threads that do simple tasks. The anonymous class below will create a thread and start it:

           ( new Thread() { public void run() { 
                  for(;       ;      ) 
                  System.out.println("Stop the world!");
                  }

             } ).start();

Thread States Or lifecycle
Threads can exist in different states. Just because a thread's start() method has been called, it does not mean that the thread has access to the CPU and can start executing straight away. Several factors determine how it will proceed.

See below diagram-

New: A new thread begins its life cycle in the new state. It remains in this state 
until the program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. 
A thread in this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task.A thread transitions back to the runnable 
state only when another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified 
interval of time. A thread in this state transitions back to the runnable state when 
that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its 
task or otherwise terminates.

Thread methods

final boolean isAlive()
This method can be used to find out if a thread is alive or dead. A thread is alive if
it has been started but not yet terminated, that is, it is not in the Dead state.

final int getPriority() 
final void setPriority(int newPriority)
The first method returns the priority of the current thread. The second method 
changes its priority. The priority set will be the minimum of the two values: the 
specified newPriority and the maximum priority permitted for this thread.

static void yield()
This method causes the current thread to temporarily pause its execution and, 
thereby, allow other threads to execute.

static void sleep (long millisec) throws InterruptedException
The current thread sleeps for the specified time before it takes its turn at running 
again.

final void join() throws InterruptedException 
final void join(long millisec) throws InterruptedException
A call to any of these two methods invoked on a thread will wait and not return 
until either the thread has completed or it is timed out after the specified time, 
respectively.

void interrupt()
The method interrupts the thread on which it is invoked. 
In the Waiting-for-notification, Sleeping, or Blocked-for-join-completion states, 
the thread will receive an InterruptedException.

static Thread currentThread()-   This method returns a reference to the Thread 
object of the currently executing thread.

final String getName() -returns the name of the thread

final void setName(String name)- sets the thread's name to the argument.

void run() -The Thread class implements the Runnable interface by providing an 
implementation of the run() method. This implementation does nothing. Subclasses
of the Thread class should override this method.If the current thread is created 
using a separate Runnable object, then the Runnable object's run() method is called.

final void setDaemon(boolean flag)-sets the status of the thread either as a daemon 
thread or as a user thread, depending on whether the argument is true or false, 
respectively. The status should be set before the thread is started.

final boolean isDaemon()-method returns true if the thread is a daemon thread, 
otherwise, false.

void start()- This method spawns a new thread, that is, the new thread will begin 
execution as a child thread of the current thread. The spawning is done 
asynchronously as the call to this method returns immediately. It throws an 
IllegalThreadStateException if the thread was already started.


That it about thread basics!!!!

If you want learn advance Threading concept click here 
We will discus a lot of new things about threading -

Like -

Joining
Deadlock
Synchronizing
Locking
wait and notify
Thread priority
Thread sheduler

Monday 4 August 2014

Why Multiple Inheritance is not supported in java?

Why multiple inheritance is not supported in java like C++? before going to explain lets see what is multiple inheritance?
Multiple inheritance is a feature of object oriented computer programming language in which an object or class can inherit characteristics and features from more than one parent object or parent class.

See diagram below (here class C is inheriting all the features of A and B)

 Above is not valid for java. e.g. multiple inheritance is not supported in java, to understand see below diagram. Here A has method m1(), B and C are getting m1() characteristic from A by single inheritance and now D is trying to get B and C characteristic e.g. m1() method. what will happen on D which m1() will be in D. This confusing case generate ambiguity. And below ambiguity problem is also called Diamond problem in multiple inheritance.


In other word we can say multiple inheritance does complicate the design and creates problem during casting, constructor chaining.

So, to avoid above issue multiple inheritance is not supported in java.
Hence we can say in other word to make simple and easy understandable and more powerful to java, It doesn't support multiple inheritance.

Thanks!!!!