Thursday 25 July 2019

Multithreading Interview Q&A

What is a Thread and What is the need for threads in Java?
What is the difference between a process and a Thread?
Which Thread by default runs in every java program?
How do you create a thread?
How do you create a thread by extending thread class?
How do you create a thread by implementing runnable interface?
How do you run a thread in Java?
What are the different states of a thread?
What is priority of a thread? What is the default priority of the Thread? How do you change the priority of a thread?
What is executorservice?
Can you give an example for executorservice?
Explain different ways of creating executor services .
How do you check whether an executionservice task executed successfully?
What is callable? How do you execute a callable from executionservice?
What is synchronization of threads?
Can you give an example of a synchronized block?
Can a static method be synchronized?
What is the use of join method in threads?
Describe a few other important methods in threads?
What is a deadlock? How can you resolve deadlock situation?
What are the important methods in Java for inter-thread communication?
What is the use of wait method?
What is the use of notify method?
What is the use of notifyall method?
Can you write a synchronized program with wait and notify methods?
How can you stop a Thread which is running?
Explain the two types of multitasking?
What is Thread scheduler?
Explain the life cycle of a Thread?
What is daemon Thread?
Cont..

Thanks..!!

Thread Group

  • Thread groups offer a convenient way to manage groups of threads as a unit.
  • A thread is always a member of a thread group.
  • A thread group not only includes threads but also other thread groups.
  • A thread group in a Java program is represented by an object of the java.lang.ThreadGroup class. 
  • The getThreadGroup() method from the Thread class returns the reference to the ThreadGroup of a thread.
Example:

public class ThreadGroupDemo {
  public static void main(String[] args) {
    Thread t1 = Thread.currentThread();

    ThreadGroup tg1 = t1.getThreadGroup();

    System.out.println("Current thread's  name:  " + t1.getName());
    System.out.println("Current thread's  group  name:  " + tg1.getName());

    Thread t2 = new Thread("my thread group");

    ThreadGroup tg2 = t2.getThreadGroup();
    System.out.println("New  thread's name:  " + t2.getName());
    System.out.println("New  thread's  group  name:  " + tg2.getName());
  }
}
 
Output:
Current thread's  name: main
Current thread's  group  name: main
New  thread's name: my thread group
New  thread's  group  name: main
  • The getParent() method from the ThreadGroup class returns the parent thread group of a thread group. The parent of the top-level thread group is null.

Thanks..!!

Wednesday 24 July 2019

How to stop, suspend and resume a Thread

Stop()
  • We can stop a Thread execution by using stop() of Thread class.
    • public void stop();
  • If we will call stop() then immediately the Thread will entered in dead state. Anyway stop() is depreciated and not recommended to use.
suspend() and resume()
  • A Thread can suspend another Thread by using suspend() method then that Thread will be paused temporarily.
    • public final void suspend();
  • A Thread can resume a suspended Thread by using resume() method then suspended Thread will continue its execution.
    • public final void resume();
  • Both methods are deprecated and not recommended to use.


Thanks..!!

Green Thread : Not recommended to use

Java multiThreading concept is implementing by using the following 2 methods :
  • GreenThread Model
  • Native OS Model
GreenThread Model
  • The Thread which is managed completely by JVM without taking underlying OS support is called green Thread.
  • Very few OS like sun Solaris provides support for green thread model.
  • Anyway green Thread model is deprecated and not recommended to use.
Native OS Model
  • The Thread which is managed by the JVM with the help of underlying OS, is called Native OS model.
  • All windows based operating systems provides support for native OS model.


Thanks..!!

Daemon Threads in Multithreading

  • The Threads which are executing in the background are called daemon Threads. Example: Garbage collector, Signal dispatcher, attach listener etc.
  • The main objective of daemon Thread is to provide support for non-daemon Thread (main Thread). For example, if main thread runs with low memory than JVM runs garbage collector to destroy useless objects. So that number of bytes of free memory will be improved, with this free memory main Thread can continue its execution.
  • Usually daemon Threads having low priority but based on our requirement daemon Threads can run with high priority also.
  • We can check deamon nature of a Thread by using isDaemon() method of Thread class.
    • public boolean isDaemon();
  • We can change daemon nature of a Thread by using setDaemon() method.
    • public void setDaemon(boolean b);
  • But changing daemon nature is possible before starting of a Thread only. After starting the Thread if we are trying to change the daemon nature we will get runtime exception saying IllegalThreadStateException.
  • By default main Thread is always non demon and all remaining Threads daemon nature will be inherited from parent to child i.e if parent thread is daemon then automatically child thread will be daemon. If parent Thread is non daemon then automatically child Thread also non daemon.
NOTE: It is impossible to change daemon nature of main Thread because it is already started by JVM at beginning. 

Example:

class MyThread extends Thread
{
}

class DaemonThreadDemo
{
              public static void main(String[] args)
              {
                             System.out.println(Thread.currentThread().isDaemon()); //main Thread
                            //Thread.currentThread().setDaemon(true)//IllegalThreadStateException
                             MyThread t=new MyThread();
                             System.out.println(t.isDaemon());//MyThread
                             t.setDaemon(true);
                             System.out.println(t.isDaemon());//MyThread
              }
}


Output:
false
false
true
  • Whenever last non-daemon Thread terminates automatically all daemon Threads will be terminated irrespective of their position.
Example:

class MyThread extends Thread
{
              public void run()
              {
                             for(int i=0;i<10;i++)
                             {
                                           System.out.println("Child Thread");
                                           try
                                           {
                                                          Thread.sleep(2000);
                                           }
                                           catch (InterruptedException e)
                                           {}
                             }
              }
}

class DaemonThreadDemo
{
              public static void main(String[] args)
              {
                             MyThread t=new MyThread();
                             t.setDaemon(true);        //-->1
                             t.start();
                             System.out.println("End of main Thread");
              }
}


Output:
End of main Thread
  • If we are commenting line 1 both main and child Threads are non-daemon. Hence both Threads will be executed until their completion.
  • If we are not commenting line 1 then main Thread is non-daemon and child Thread is daemon. Hence whenever main Thread terminates automatically child Thread will be terminated. In this case output is “End of main Thread” followed by “Child Thread” or sometimes we may get “End of main Thread” or “Child Thread” followed by “End of main Thread”.
Thanks..!!

Sunday 21 July 2019

Deadlock in Multithreading

  • If two threads are waiting for each other forever such type of situation (infinite waiting) is called deadlock.
  • Synchronized keyword is the only reason for deadlock situation. Hence while using Synchronized keyword we have to take special care.
  • There are no resolution techniques for deadlock but several prevention techniques are available.
Example:

class A
{
              public synchronized void foo(B b)
              {
                             System.out.println("Thread1 starts execution of foo() method");
                             try
                             {
                                           Thread.sleep(2000);
                             }
                             catch (InterruptedException e)
                             {}
                             System.out.println("Thread1 trying to call b.last()");
                             b.last();
              }
              public synchronized void last()
              {
                             System.out.println("inside A, this is last()method");
              }
}

class B
{
              public synchronized void bar(A a)
              {
                             System.out.println("Thread2 starts execution of bar() method");
                             try
                             {
                                           Thread.sleep(2000);
                             }
                             catch (InterruptedException e)
                             {}
                             System.out.println("Thread2 trying to call a.last()"); a.last();
              }
              public synchronized void last()
              {
                             System.out.println("inside B, this is last() method");
              }
}

class DeadLock implements Runnable
{
              A a=new A(); B b=new B();
              DeadLock()
              {
                             Thread t=new Thread(this);
                             t.start(); 
                             a.foo(b);//main thread
              }
              public void run()
              {
                             b.bar(a);//child thread
              }
              public static void main(String[] args)
              {
                             new DeadLock();//main thread
              }
}

Output:
Thread1 starts execution of foo() method
Thread2 starts execution of bar() method
Thread2 trying to call a.last()
Thread1 trying to call b.last()
//here cursor always waiting.

Note: If we remove at least one synchronized keyword then we won't get DeadLock. Hence synchronized keyword in the only reason for DeadLock due to this while using synchronized keyword we have to handling carefully.

Deadlock vs Starvation:
  • Long waiting of a Thread where waiting never ends is called deadlock.
  • Whereas long waiting of a Thread where waiting ends at certain point is called starvation.
  • For example, low priority Thread has to wait until completing all high priority Threads. It may be long waiting but ends at certain point, which is nothing but starvation.

Thanks..!!